Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
Adding a JSON elements to an Array of JSON in Javascript

I have JSON and JSON array and I want to push every elements of JSON to JSON array with some condition.

Here is my code:

let json = { Jack: 10, Merry: 29, Charles: 37, Lahm: 0 }
let jsonArray = [
    {
        match: {
            Ashley: 46,
        },
    },
]

for (const key in json) {
    if (json[key] !== 0) {
        jsonArray.push({
            match: `{${key}: ${json[key]}}`,
        })
    }
}
 

I get the following response:

[
  { match: { Ashley: 46 } },
  { match: '{Jack: 10}' },
  { match: '{Merry: 29}' },
  { match: '{Charles: 37}' }
]

The problem is that pushed elements has single quotes which I don't want. Is there a way to push those elements without quotes?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Note that you're not really working with JSON. JSON is a string representation of JavaScript objects. What you have is simply a plain JS object, and also an array of objects.

Your issue is that you're simply passing a string into match, and not an actual object, when you are using template literals.

Instead, use bracket notation to use the value of the key variable in your new match object, i.e.:

match: { [key]: json[key] }

See proof-of-concept example:

let myObject = {
  Jack: 10,
  Merry: 29,
  Charles: 37,
  Lahm: 0
}
let myArrayOfObjects = [{
  match: {
    Ashley: 46,
  },
}, ]

for (const key in myObject) {
  if (myObject[key] !== 0) {
    myArrayOfObjects.push({
      match: {
        [key]: myObject[key]
      }
    })
  }
}

console.log(myArrayOfObjects);


This is also a good chance to explore the use of Object.entries, since it actually returns the a [key, value] tuple:

let myObject = {
  Jack: 10,
  Merry: 29,
  Charles: 37,
  Lahm: 0
}
let myArrayOfObjects = [{
  match: {
    Ashley: 46,
  },
}, ]

Object.entries(myObject).forEach(([key, value]) => {
  if (value !== 0) {
    myArrayOfObjects.push({
      match: {
        [key]: value
      }
    })
  }
});

console.log(myArrayOfObjects);

about 4 years ago · Juan Pablo Isaza Denunciar

0

The problem is that you are pushing an object with a template string in it to the array. You need to change the syntax a little bit.

for (const key in json) {
    if (json[key] !== 0) {
        jsonArray.push({
            match: {[key]: json[key]}
        })
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to access the key/value pairs of the JS object, and not add a string to the array. Once that's completed for all the properties - if you need to - you can then stringify the array to JSON.

const obj = { Jack: 10, Merry: 29, Charles: 37, Lahm: 0 };
const arr = [ { match: { Ashley: 46 } }];

for (const key in obj) {
  arr.push({
    match: { [key]: obj[key] }
  });
}

console.log(arr);
console.log(JSON.stringify(arr));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda