2

i have a json object data in the below format. In that i need to insert some new record after particular id.

    [
       {
          "id":"1",
          "name":"one",
          "children":[
             {
                "id":"4",
                "name":"four",
                "children":[

                ]
             },
             {
                "id":"5",
                "name":"five",
                "children":[

                ]
             },
             {
                "id":"6",
                "name":"six",
                "children":[

                ]
             }
          ]
       }       
    ]

For Ex: i have a id as 5 and also new JSON object({"id":"new data","name":"new data","children":[]}) as well. then the new data should insert after id 5. Is there any possible way to insertafter some particular id.

        [
       {
          "id":"1",
          "name":"one",
          "children":[
             {
                "id":"4",
                "name":"four",
                "children":[

                ]
             },
             {
                "id":"5",
                "name":"five",
                "children":[

                ]
             }, 
             {
                "id":"new data",
                "name":"new data",
                "children":[

                ]
             },
             {
                "id":"6",
                "name":"six",
                "children":[

                ]
             }
          ]
       }
    ]
4

1 Answer 1

2

Here is a quick sample with splice ;) Just pass the target array, the object, and the id, and the add function will insert your new object into the target at the proper place.

const data = [{
  "id":"1",
  "name":"one",
  "children":[
     {
        "id":"4",
        "name":"four",
        "children":[]
     },
     {
        "id":"5",
        "name":"five",
        "children":[]
     },
     {
        "id":"6",
        "name":"six",
        "children":[]
     }
  ]
}];

const object = {"id":"new data","name":"new data","children":[]};

const add = (object, toArray, afterId) => {
  const afterIndex = toArray.findIndex(item => item.id === afterId);
  toArray.splice(afterIndex + 1, 0, object);
};

add(object, data[0].children, '5');
console.log(data);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.