-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!

5
  • new account - same question Commented Jan 29, 2018 at 13:37
  • JSON, is a string. Commented Jan 29, 2018 at 13:39
  • @messerbill Should post the link as well Commented Jan 29, 2018 at 13:39
  • Welcome to SO. Please visit the help center to see what and How to Ask. HINT: Post effort and code Commented Jan 29, 2018 at 13:39
  • the question was already closed i cannot find it anymore - this was some days ago Commented Jan 29, 2018 at 13:39

1 Answer 1

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.

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

3 Comments

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.
Thank you @ele. Actually I took a different approach to achieve the goal. Your solution works great. Thanks!
@KaustavRoy great. An accepted answer would be nice :-)

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.