javascript - Add element for object -
i need go through list of objects find element , add new element root, can scroll through list , find element, can not add correct level
var data = [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4, "children": [ { "id": 6 }, { "id": 7 } ] }, { "id": 5 } ]; function findbyid(data, id, element) { function iter(a) { if (a.id === id) { a.push(element); // error result = a; return true; } return array.isarray(a.children) && a.children.some(iter); } var result; data.some(iter); return result } var element = { "children": [{"id": 6}] }; findbyid(data, 5, element); document.write('<pre>' + json.stringify(data, 0, 4) + '</pre>');
use object.assign
merge properties element
object current object of iteration.
var data = [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4, "children": [ { "id": 6 }, { "id": 7 } ] }, { "id": 5 } ]; function findbyid(data, id, element) { function iter(a) { if (a.id === id) { object.assign(a, element); result = a; return true; } return array.isarray(a.children) && a.children.some(iter); } var result; data.some(iter); return result } var element = { "children": [{"id": 6}] }; findbyid(data, 5, element); console.log(data);
Comments
Post a Comment