Get value from key of parent and pass it to children key in object

j.doe :

I have structure like below:

{
  0: [{
    "id": "1",
    "parentId": "root",
    "path": "root"
    "children": [{
      "id": "2",
      "parentId": "1",
      "path": "1/2",
      "children": [
        "id": "4",
        "parentId": "2",
        "path": "2/4"
      ]
    }, {
      "id": "3",
      "parentId": "1",
      "path": "1/3"
    }]
  }]
}

I have key "path" and now it's "parentId/id", but I would like to have path from root to this element, so it should looks "root/parentId/id/parentId/it..." etc. For example path: "root/1/2/4".

How can I dynamically put a value inside key "path" to get full path to root element?

Guerric P :

Your data structure does not respect the childhood of each element, but considering this is not a part of the question, here is a simple recursive solution:

const data = [{
    "id": "1",
    "parentId": "root",
    "path": "root",
    "children": [{
        "id": "2",
        "parentId": "1",
        "path": "1/2",
        "children": [{
            "id": "4",
            "parentId": "2",
            "path": "2/4"
          }
        ]
      }, {
        "id": "3",
        "parentId": "1",
        "path": "1/3"
      }
    ]
  },
  {
    "id": "4",
    "parentId": "2",
    "path": "2/4"
  }
];

function assignPath(tree, index, array, currentPath) {
  tree.path = currentPath || 'root';
  tree.children && tree.children.forEach(child => {
    assignPath(child, null, null, `${tree.path}/${child.id}`);
  });
}

data.forEach(assignPath);

console.log(data);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=410726&siteId=1