【问题标题】:Javascript, finding object's parents in a JSONJavascript,在 JSON 中查找对象的父对象
【发布时间】:2017-09-20 14:33:51
【问题描述】:

我有一个像这样的 Json 文件:

{
    "id": 1,
    "name": "node",
    "nodes": [
      {
        "id": 2,
        "name": "node",
        "nodes": [
          {
            "id": 3,
            "name": "node",
            "nodes": []
          }
        ]
      },

我想要一个函数,我可以在其中传递对象的“id”,并且可以获得所有父节点“id”属性的列表。我想我问的是一个递归函数,它以一种方式获得所需的“id”,然后返回树并为每个父级推送所有“id”值(如何,我不知道)。 这在 JavaScript / Lodash 中可行吗?

【问题讨论】:

标签: javascript json object lodash


【解决方案1】:

您可以通过以下方式这样做

let obj = {
    "id": 1,
    "name": "node",
    "nodes": [
      {
        "id": 2,
        "name": "node",
        "nodes": [
          {
            "id": 3,
            "name": "node",
            "nodes": []
          }
        ]
      }
   ]
}
//console.log(obj);

function find(obj, id){
    if(obj.id == id){
        return [id];
    }
    let result = [];
    for(element of obj.nodes){
        //console.log('p', obj.id, 'c', element);
        result = result.concat(find(element, id));
    }
    //console.log(result);
    if(result.length > 0){
        result.push(obj.id);
    }
    return result;
}

console.log(find(obj, 3));

【讨论】:

  • 谢谢,这似乎有效。如果我想使用对象数组怎么办?
  • 你看我是如何使用 for..of 循环调用内部数组的,你可以简单地在外部函数中调用它
【解决方案2】:

我想我问的是一个递归函数,它以一种方式获得所需的“id”,然后返回树并推送每个父级的所有“id”值(如何,我不知道)

对。很复杂,你不觉得吗?

你为什么不垫那种东西:

var data = {
  "id": 1,
  "name": "node",
  "nodes": [{
    "id": 2,
    "name": "node",
    "nodes": [{
      "id": 3,
      "name": "node",
      "nodes": []
    }]
  }]
}

var nodesById = Object.create(null);
//quickly indexing the nodes, 
//and adding them a reference to their parentId
(function _(parentId, node){
  node.parentId = parentId;
  nodesById[node.id] = node;
  if(node.nodes)
    node.nodes.reduce(_, node.id);
    
  return parentId; //for the reduce()
})(null, data);

function getParent(node){
  return nodesById[node.parentId];
}

现在查找任何节点只需在该地图中进行简单查找即可。

【讨论】:

    猜你喜欢
    • 2018-08-30
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 2020-12-19
    • 2010-10-05
    相关资源
    最近更新 更多