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);
}
});
}
答案 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);
}
});
}