How to access immediate parent record from child record in loop?

时间:2017-07-12 08:20:21

标签: javascript

Below is my JSON:

var records = 
[
  {
    "name": "Node-1",
    "nodes": [
      {
        "name": "Node-1-1",
         "parentName" : null,
        "nodes": [
          {
            "name": "Node-1-1-1",
            "parentName" : null,
            "nodes": []
          }
        ]
      }
    ]
  }
];

Now I want that each child record to have its parent name in parentName property.

For example: parentName for Node-1-1 should be Node-1 because Node-1 is parent of Node-1-1

But here I am not getting that how would I will know that Node-1 is parent of Node-1-1 and how I would access Node-1 value when I am reading Node-1-1 record?

Expected output:

[
  {
    "name": "Node-1",
    "nodes": [
      {
        "name": "Node-1-1",
         "parentName" : "Node-1",
        "nodes": [
          {
            "name": "Node-1-1-1",
            "parentName" : "Node-1-1",
            "nodes": []
          }
        ]
      }
    ]
  }
];

var records = 
[
  {
    "name": "Node-1",
    "nodes": [
      {
        "name": "Node-1-1",
         "parentName" : null,
        "nodes": [
          {
            "name": "Node-1-1-1",
            "parentName" : null,
            "nodes": []
          }
        ]
      }
    ]
  }
];
Iterate(records);

function Iterate(nodes)
    {
 	nodes.forEach(function (node) {
       if (node.nodes) {
                Iterate(node.nodes);
            }
 	});
    }

2 个答案:

答案 0 :(得分:2)

您可以将父项作为另一个参数传递给Iterate方法。



var records = [{
  "name": "Node-1",
  "nodes": [{
    "name": "Node-1-1",
    "parentName": null,
    "nodes": [{
      "name": "Node-1-1-1",
      "parentName": null,
      "nodes": []
    }]
  }]
}];
Iterate(records);

function Iterate(nodes, parent) {
  nodes.forEach(function(node) {
    if (parent) {
      node.parentName = parent.name;
    }
    if (node.nodes) {
      Iterate(node.nodes, node);
    }
  });
}

console.log(records);




答案 1 :(得分:2)

只需将parentName作为Iterate函数的参数传递。



var records = [
  {
    "name": "Node-1",
    "nodes": [
      {
        "name": "Node-1-1",
         "parentName" : null,
        "nodes": [
          {
            "name": "Node-1-1-1",
            "parentName" : null,
            "nodes": []
          }
        ]
      }
    ]
  }
];

Iterate(records);

console.log(records);

function Iterate(nodes, parentName) {
    nodes.forEach(node => {
    if (parentName) {
      node.parentName = parentName;
    }

    if (node.nodes) {
      Iterate(node.nodes, node.name);
    }
  });
}