首页 > 解决方案 > 从父键获取值并将其传递给对象中的子键

问题描述

我的结构如下:

{
  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"
    }]
  }]
}

我有 key "path",现在是"parentId/id",但我想有从根到这个元素的路径,所以它应该看起来"root/parentId/id/parentId/it..."等等。例如 path: "root/1/2/4"

如何动态地将值放入键"path"中以获取根元素的完整路径?

标签: javascriptarraysobject

解决方案


您将需要识别根节点并从其路径开始。

然后将每个连续的子 id 添加到路径末尾。

let obj = {
  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"
    }]
  }]
};

console.log(getRoute(obj[0][0], true)); // Identify root

function getRoute(node, isRoot) {
  return node != null
    ? (isRoot
      ? (node.path + '/')
      : ''
    ) + node.id + (node.children
      ? '/' + getRoute(node.children[0], false)
      : '')
    : '';
}


推荐阅读