'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?
Solution 1:[1]
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));
Solution 2:[2]
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);
Solution 3:[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]}
})
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Andy |
Solution 2 | |
Solution 3 | Palladium02 |