Constructively manipulating any value/object within a JSON tree of unknown depth Constructively manipulating any value/object within a JSON tree of unknown depth json json

Constructively manipulating any value/object within a JSON tree of unknown depth


If you want to modify a node, like you said, you can just modify the properties of that node.

var node = findNode.find("nodeid_3",json);node.id = "nodeid_3_modified";node.children = [];

Also, why are you using jQuery for this?

Here's an alternative without using jQuery should work:

function findNode(object, nodeId) {   if (object.id === nodeId) return object;   var result;   for (var i = 0; i < object.children.length; i++) {      result = findNode(object.children[i], nodeId);      if (result !== undefined) return result;   }}


That is not JSON, it is a Javascript object literal. JSON is a certain way to encode a simple Javascript object into a string; your example is not written that way. Also, your code does not manipulate JSON objects (which are actually strings, not objects); it manipulates Javascript objects (which is a way simpler task).

That said, I'm not sure what your actual question is, but if it's about adding new elements to the children array, you can use Array.push:

findNode.find("nodeid_3",json);findNode.node.children.push(child);

(This assumes that findNode.find actually works, which I'm pretty sure it does not.)