【问题标题】:How to fetch parent ids recursively from json strings如何从json字符串中递归获取父ID
【发布时间】:2020-02-19 07:36:55
【问题描述】:
{
  "id": "1",
  "name": "root",
  "children": [
    {
      "id": "1.1",
      "name": "Child 1",
      "children": [
        {
          "id": "1.1.1",
          "name": "Child 1-1",
          "children": [
            {
              "id": "1-1-1",
              "name": "Child 1-1-1",
              "children": [

              ]
            }
          ]
        },
        {
          "id": "1.1.2",
          "name": "Child 1-2",
          "children": [

          ]
        },
        {
          "id": "1.1.3",
          "name": "Child 1-3",
          "children": [

          ]
        }
      ]
    },
    {
      "id": "1.2",
      "name": "Child 2",
      "children": [
        {
          "id": "1.2.1",
          "name": "Child 2-2",
          "children": [

          ]
        }
      ]
    }
  ]
}

这是作为响应的 JSON 字符串。必须递归地获取父元素的所有父 ID。

例如,输入是 1.2.1 然后它返回 [1.2] 输入为 1.1.3 然后返回 [1.1, 1]

我怎样才能做到这一点?

【问题讨论】:

  • 请展示您的尝试。如果你还没有尝试过任何东西,你应该这样做。如果没有体面的尝试,您就是客户。没有人是为客户而来的。
  • @user630209 你能解释一下逻辑吗,据我所知,如果你必须得到所有父母的身份证,那么如果你的输入是 1.2.1 那么输出应该是 [1.2, 1] , 如果我错了,请纠正我。
  • 看看this

标签: javascript json angular


【解决方案1】:

只是一个使用 dfs 的简单递归

const data = JSON.parse('{"id":"1","name":"root","children":[{"id":"1.1","name":"Child 1","children":[{"id":"1.1.1","name":"Child 1-1","children":[{"id":"1-1-1","name":"Child 1-1-1","children":[]}]},{"id":"1.1.2","name":"Child 1-2","children":[]},{"id":"1.1.3","name":"Child 1-3","children":[]}]},{"id":"1.2","name":"Child 2","children":[{"id":"1.2.1","name":"Child 2-2","children":[]}]}]}')

function dfs (target, node) {
  if (node.id === target) { return node.id }
  if (!node.children) { return false } // we could even skip that line since in your data you seem to have an empty array
  const has = node.children.find(c => dfs(target, c))
  return has && [node.id].concat(has.id)
}
console.log(dfs('1.2.1', data))
console.log(dfs('1.1.3', data))

【讨论】:

    【解决方案2】:

    您可以采用迭代和递归的方法,并且

    • chcek 如果给定的数据不是对象,则返回
    • 检查id,如果找到则返回一个空数组,由调用函数填充
    • 迭代children,发现短路并再次调用该函数。

    function getParentIds(object, id) {
        var ids;
        if (!object || typeof object !== 'object') return;          // no object
        if (object.id === id) return [];                            // id found
        return object.children.some(o => ids = getParentIds(o, id)) // call recursive function
            ? [...ids, object.id]                                   // if found, take ids
            : undefined;                                            // otherwise return falsy
    }
    
    var data = { id: "1", name: "root", children: [{ id: "1.1", name: "Child 1", children: [{ id: "1.1.1", name: "Child 1-1", children: [{ id: "1-1-1", name: "Child 1-1-1", children: [] }] }, { id: "1.1.2", name: "Child 1-2", children: [] }, { id: "1.1.3", name: "Child 1-3", children: [] }] }, { id: "1.2", name: "Child 2", children: [{ id: "1.2.1", name: "Child 2-2", children: [] }] }] };
    
    console.log(getParentIds(data, '1.2.1')); // ['1.2']
    console.log(getParentIds(data, '1.1.3')); // ['1.1', '1']
    console.log(getParentIds(data, 'foo'));   // undefined
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案3】:

      您必须解析完整的对象以递归地将父 id 注入子对象。这样的事情会做的事情。

      function injectParents(data, parents) {
          if(!parents) {
              parents = [];
          }
          parents.push(data.id);
          data.children.map(child=>{
              child.parents = parents;
              if(child.children && child.children.length>0) {
                  child = injectParents(child, Array.from(parents));
              }
              return child;
              });
          return data;    
      }
      

      那么你通常会这样称呼它

      const injectedResponse = injectParents(response, null);
      

      【讨论】:

        【解决方案4】:

        你可以使用

        for(let x in arrayName){
           //here you can access the json 
           console.log(arayName(x).id)
        }
        

        【讨论】:

          【解决方案5】:

          这就是你要找的东西吗?

          //Input
          let input = '1.2.1';
          
          //Data
          data = JSON.parse('{"id":"1","name":"root","children":[{"id":"1.1","name":"Child 1","children":[{"id":"1.1.1","name":"Child 1-1","children":[{"id":"1-1-1","name":"Child 1-1-1","children":[]}]},{"id":"1.1.2","name":"Child 1-2","children":[]},{"id":"1.1.3","name":"Child 1-3","children":[]}]},{"id":"1.2","name":"Child 2","children":[{"id":"1.2.1","name":"Child 2-2","children":[]}]}]}')
          
          //Main function start here
          function findIdWhereChild(data, input) {
            if (data.children?.find(x => x.id == input)) {
              return data.id;
            }
            else {
              if (data.children.length > 0) {
                for (let i = 0; i < data.children.length; i++) {
                  let findalResult = findIdWhereChild(data.children[i], input);
                  if (findalResult) {
                    return findalResult;
                  };
                };
          
              } else {
                return undefined;
              }
            }
          };
          
          //Execution LOGs
          console.log(findIdWhereChild(data, input));

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-06-14
            • 1970-01-01
            • 1970-01-01
            • 2016-08-02
            • 1970-01-01
            • 2017-07-25
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多