2

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" }
        ]
}
4
  • Where do you want to put the merged array in the object? Commented Dec 7, 2020 at 16:36
  • either concat it to batter array or topping array -- either or, just curious as to how to do it Commented Dec 7, 2020 at 16:37
  • where ? in foo.batters.batter or in foo.topping or in foo.newOne, ? , and what will happent to previous lists ? Commented Dec 7, 2020 at 16:38
  • foo.batters.batter = foo.batters.batter.concat(foo.topping) Commented Dec 7, 2020 at 16:38

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

foo.batters.batter = [...foo.batters.batter, ...foo.topping];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.