Constructive control of any value / object in the JSON tree of unknown depth

I have a JSON tree that contains nodes and children - format:

jsonObject = 
{
  id:nodeid_1,
  children: [
  {
    id:nodeid_2,
    children:[]
  },
  {
    id:nodeid_3,
    children:[
    {
      id:nodeid_4,
      children:[]
    },
    {
      id:nodeid_5,
      children:[]
    }
  }
}

I do not know the depth of this tree, node is able to have many children, who also have many children, etc.

My problem is that I need to add nodes to this tree using nodeID. For example, a function that can accept a nodeID and a node object (including its children) can replace this node inside the tree, which will become a large tree as a result.

I only came across recursive functions that allow me to move through all the nodes in the JSON tree, and the modification I made from one of these functions returns me a node object - but it does not help me, since I need to change the source tree:

var findNode = {
node:{},
find:function(nodeID,jsonObj) {
    if( typeof jsonObj == "object" ) {
        $.each(jsonObj, function(k,v) {
            if(v == nodeID) {
                findNode.node = $(jsonObj).eq(0).toArray()[0];        
            } else {
                findNode.find(nodeID,v); 
            }
        });
    } else {
        //console.log("jsobObj is not an object");
    }
  }
}

:

findNode.find("nodeid_3",json);
alert(findNode.node);

, - JSON ?

+3
2

node, , node.

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

, jQuery ?

jQuery :

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;
   }
}
+1

JSON, Javascript. JSON - Javascript ; . , JSON ( , ); Javascript ( ).

, , , children, Array.push:

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

( , findNode.find , , .)

+1

Source: https://habr.com/ru/post/1764554/


All Articles