cherrytree
cherrytree

Reputation: 45

Append data dynamically to existing JSON

Given the following JSON structure,

#JSON 1
     {
            "objects": 
             [
                {
                    "type": "chocolate",
                    "id": "c1"
                },
                {
                    "type": "sweet",
                    "id": "s1"
                }
            ]
      }

How do I append data dynamically using Javascript? Something like this:

#JSON 2
         [
           {
            "data": {      
                    "type": "chocolate",
                    "id": "c1"
                }
            },
            {
            "data": {
                    "type": "sweet",
                    "id": "s1"
                }
            }
        ]

I've used the fetch API to read the file as it is a huge JSON file. and I do not want to hardcode type and id. What would be a better way to do this?

Upvotes: 1

Views: 652

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

obviously you're getting this result from fetch, but for the purposes of demonstrating what you need to do I'm initialising it inline

let result = { 
    "type": "test",
    "id": "123",
    "objects": 
    [
        {
            "type": "chocolate",
            "id": "c1"
        },
        {
            "type": "sweet",
            "id": "s1"
        }
    ]
};
let finalResult = result.objects.map(data => ({data}));
console.log(finalResult);

You mention using fetch - it'd be simply like

fetch(url)
.then(result => result.json())
.then(result => result.objects.map(data => ({data})))
.then(finalResult => {
    // here the result is in the format you want
    console.log(finalResult);
});

Upvotes: 1

Related Questions