Reputation: 53
Given a JSON object, how would you merge the batter
array and topping
array within the object. I know I can do let x = foo.batters.batter.concat(foo.topping)
, which will give me an array of the merged array but what if I wanted it within object?
foo = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
Upvotes: 2
Views: 63
Reputation: 21
Your answer is partially true. But you didn't add the value to the foo object.
You can do it like this:
foo.mergedArray = foo.batters.batter.concat(foo.topping);
After that, when you call foo.mergedArray
you can access merged array of batter
and topping
.
If one of the batter
and topping
has changed foo.mergedArray
will not be updated. Because foo.mergedArray
has its own referance.
Upvotes: 2
Reputation: 6336
Try this:
foo.batters.batter = [...foo.batters.batter, ...foo.topping];
Upvotes: 1