如何在json对象中获取父母ID列表

詹斯马

我的嵌套 json 数组如下所示:

 [
      {
        id: 1,
        name: "Mike",
        children: [
          { id: 2, name: "MikeC1" },
          { id: 3, name: "MikeC2" },
          {
            id: 4, name: "MikeC3",
            children: [{ id: 5, name: "MikeCC1" }]
          },
        ]
      },
      {
        id: 6,
        name: "Json",
        children: [
          { id: 7, name: "JsonC1" },
          { id: 8, name: "JsonC2" },
          {
            id: 9, name: "JsonC3",
            children: [{ id: 10, name: "JsonCC1" },{ id: 11, name: "JsonCC2" }]
          },
        ]
      }
    ]

现在我得到一个像“11”这样的id

然后在 json 中获取父 ids 数组,如 [6,9,11]

怎么做?

var id = 11
console.log(findParent(id))
//result is [6,9,11]
援助在线01

你需要做递归搜索

 const persons = [
      {
        id: 1,
        name: "Mike",
        children: [
          { id: 2, name: "MikeC1" },
          { id: 3, name: "MikeC2" },
          {
            id: 4, name: "MikeC3",
            children: [{ id: 5, name: "MikeCC1" }]
          },
        ]
      },
      {
        id: 6,
        name: "Json",
        children: [
          { id: 7, name: "JsonC1" },
          { id: 8, name: "JsonC2" },
          {
            id: 9, name: "JsonC3",
            children: [{ id: 10, name: "JsonCC1" },{ id: 11, name: "JsonCC2" }]
          },
        ]
      }
    ];
    
    function searchRecursive(items, id) {
      const allIds = [];
      
      items.forEach(item => {
        if(item.id === id) {
          allIds.push(item.id);
        }
        else if(item.children) {
          const ids = searchRecursive(item.children, id);
          
          if(ids.length) allIds.push(item.id);
          
          ids.forEach(id => allIds.push(id));
        }
      });
      
      return allIds;
    }
    
    console.log(searchRecursive(persons, 11));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

获取json对象中的父母ID列表

如何在jstree中获取父母和父母的父母ID

如何在 Javascript 中从 JSON 格式获取对象 ID

如何在Angular 2中通过id获取.json对象?

如何在Java中获取JSON对象的ID

Django / python如何从对象列表中获取ID列表

如何在JSON数组中的对象内获取JSON对象

在 Postgres 中执行 SELECT 语句时,如何从 JSONB 字段中获取 JSON 对象列表而不是 ID 列表?

如何在webAPi中将对象列表获取到JSon

如何获取子数组对象中可用的ID列表

如何在JPA / Hibernate的孩子的ID中引用父母的ID?

如何在对象内部的json对象中获取数据?

从 id 列表中获取对象列表 javascript

如何在JMESPath中获取对象键列表

如何在数组列表中获取对象的PHP

如何在列表中获取最大对象并替换它?

如何在列表中获取游戏对象的组件

如何在javascript中获取对象属性列表?

如何在我的 JSON 对象中获取相应的 JSON 值?

如何在REST API中从Json数组获取JSON对象

如何在Json ..中获取JSON对象的值?

如何从 Json 格式的 POST 请求中获取对象列表

如何在git中获取合并提交的父母?

如何在javascript中获取父母的孩子的价值

如何在下拉列表中获取所选选项的ID?

如何在woocommerce中按产品ID获取产品列表

如何在Netsuite中获取内部ID列表

如何在NHibernate中获取具有ID的商品列表

如何在 ActiveAdmin 中获取新创建对象的 ID?