-2

I am building a JSON file dynamically. I want to add a JSON array in the JSON object. The JSON looks like-

{"name":"Root",
  "children":[
   {"name":"child1"},
   {"name":"child2"}
  ]}

Now, I want to add -

[{"name":"child11"},{"name":"child12"}]

under "child1" object. How to do it? I have also tried keeping blank children object while creating the original JSON object, but JSON parser doesn't keep those empty children block. In current scenario, when I am using push() function to add new child it throws exception. Any help is much appreciated. Thanks in advance!!

Edit1: I think I didn't made myself clear enough. I have researched SO before posting this question, and I guess this is not a duplicate question. My target JSON is -

{
  "name": "Root",
  "children": [{
      "name": "child1",
   "children": [{
  {"name": "child11"},
  {"name": "child12"}
   }]
    },
    {
      "name": "child2",
   "children": [{
  {"name": "child21"},
  {"name": "child22"}
   }]
    }
  ]
};

Here is the code snippet that I am trying to run -

flare = {
  "name": "Root",
  "children": [{
      "name": "child1",
   "children": [{
  {"name": "child11"},
  {"name": "child12"}
   }]
    },
    {
      "name": "child2",
   "children": [{
  {"name": "child21"},
  {"name": "child22"}
   }]
    }
  ]
};
var updatedJson = twoLevelSelection(flare);
function twoLevelSelection(json){
 var root = flare.name;
 var string_json = '';
 string_json = '{"name": "'+root+'","children": [';
 flare.children.forEach(
 function(d){
  string_json = string_json+ '{"name":"'+d.name+'","children":[]},';
 }
 );
 string_json = string_json.substring(0,string_json.length-1);
 string_json = string_json + ']}';
 return JSON.parse(string_json);
}
// data is the original data.i.e - flare
// d is the clicked node, under which children to be added
function traverse(data,d){
var queue = [];
var next = data;
while(next){
 if(next.children){
  next.children.forEach(
  function(k){
   queue.push(k);
  }
  )
 }
 if(queue[0].name==d.name){
  alert(queue[0].children);
  //d.children = queue[0].children;
  var child_string='';
  var child_array = [];
  queue[0].children.forEach(
  function(j){
   child_string = '{"name": "'+j.name+'"}';
   child_array.push(child_string);
  }
  );
  console.log(child_array);
  d.children = [...child_array];
  console.log(updatedJson);
  //update(updatedJson);
  break;
 }else{
  next= queue.shift();
 }
}
}
The traverse() will be called on a click event. Sorry, for not providing clarity at first place. Thanks!
Kaustav Roy
  • 49
  • 1
  • 5

1 Answers1

2

You can use the Spread Operator to accomplish that.

This code snippet has a function called addElements which find the target and adds the new elements to the children array.

var obj = {
  "name": "Root",
  "children": [{
      "name": "child1"
    },
    {
      "name": "child2"
    }
  ]
};


var newArray = [
   { "name": "child11"}, 
   { "name": "child12"}
];

var addElements = function(target, array) {
  obj.children.forEach(function(child) {
    if (child.name === target) {
      child['children'] = [...(child['children'] || []), ...newArray];
      return;
    }
  });
};

addElements('child1', newArray);


console.log(obj);

See? now your obj.childre[0].children array contains the new elements.

Ele
  • 33,468
  • 7
  • 37
  • 75
  • Thank you for the response. I wasn't clear about my query. Actually, I want to add new children under "child1" not under "root". Please find the edit and the code above. – Kaustav Roy Jan 30 '18 at 06:45
  • Thank you @ele. Actually I took a different approach to achieve the goal. Your solution works great. Thanks! – Kaustav Roy Feb 02 '18 at 09:28
  • 1
    @KaustavRoy great. An accepted answer would be nice :-) – Ele Feb 02 '18 at 09:37