0

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?

2
  • 4
    There is no JSON here. Just JS arrays and objects.
    – Andy
    CommentedFeb 9, 2022 at 7:25
  • 1
    Specifically, JSON is always a single string whose content is of a certain format.
    – Ouroborus
    CommentedFeb 9, 2022 at 7:29

3 Answers 3

5

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);

    3

    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]} }) } } 
      2

      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));

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.