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":[

                ]
             }
          ]
       }
    ]
Vijay Baskaran
  • 869
  • 2
  • 9
  • 18
  • Use `splice`. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice – sjahan Jul 24 '18 at 13:12
  • JSON is in nested format so how could i use splice.? – Vijay Baskaran Jul 24 '18 at 13:15
  • Possible duplicate of [Adding a new array element to a JSON object](https://stackoverflow.com/questions/18884840/adding-a-new-array-element-to-a-json-object) – Ullas Hunka Jul 24 '18 at 13:15
  • As @sjahan said you should use `splice`. there is another link: https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index – Mort Jul 24 '18 at 13:22

1 Answers1

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);
sjahan
  • 5,720
  • 3
  • 19
  • 42