0

我有点陷入一种解决方案

我有一个嵌套数组,我想使用键 id 查找任何父或子的索引,这是示例 json

[
  {
    "id": "1",
    "Name": "John Doe",
    "children": [
      {
        "id": "1.1",
        "name": "John doe 1.1"
      },
      {
        "id:": "1.2",
        "name:": "John doe 1.2"
      },
      {
        "id": "1.3",
        "name": "John doe 1.3",
        "children": [
          {
            "id": "1.3.1",
            "name": "John doe 1.3.1"
          }
        ]
      }
    ]
  },
  {
    "id": "2",
    "Name": "Apple",
    "children": [
      {
        "id": "2.1",
        "name": "Apple 2.1"
      },
      {
        "id:": "1.2",
        "name:": "Apple 1.2"
      }
    ]
  }
]

我想找到父或子数组对象的索引以添加该父或子的子对象

所以基本上它将是 n 级的嵌套数组

4

2 回答 2

1

Array.find 或 filter 将为父母做。

let found = data.find(each => each.id == '2');
console.log(found);
let foundChild = found.children.find(child => child.id == '1.2');
console.log(foundChild);

用过滤器替换查找

于 2021-02-22T17:51:19.653 回答
1

这是使用对象扫描的灵活迭代解决方案

// const objectScan = require('object-scan');

const myData = [ { id: '1', Name: 'John Doe', children: [ { id: '1.1', name: 'John doe 1.1' }, { 'id:': '1.2', 'name:': 'John doe 1.2' }, { id: '1.3', name: 'John doe 1.3', children: [ { id: '1.3.1', name: 'John doe 1.3.1' } ] } ] }, { id: '2', Name: 'Apple', children: [ { id: '2.1', name: 'Apple 2.1' }, { 'id:': '1.2', 'name:': 'Apple 1.2' } ] } ];

const getNode = (data, id) => objectScan(['**(^children$).id'], {
  useArraySelector: false,
  abort: true,
  rtn: 'parent',
  filterFn: ({ value }) => value === id
})(data);
const getNodeWithParents = (data, id) => objectScan(['**(^children$).id'], {
  useArraySelector: false,
  abort: true,
  rtn: 'parents',
  filterFn: ({ value }) => value === id
})(data);

console.log(getNode(myData, '2.1'));
// => { id: '2.1', name: 'Apple 2.1' }
console.log(getNodeWithParents(myData, '2.1'));
/* =>
[
{ id: '2.1', name: 'Apple 2.1' },
[ { id: '2.1', name: 'Apple 2.1' }, { 'id:': '1.2', 'name:': 'Apple 1.2' } ],
{ id: '2', Name: 'Apple', children: [ { id: '2.1', name: 'Apple 2.1' }, { 'id:': '1.2', 'name:': 'Apple 1.2' } ] },
[ { id: '1', Name: 'John Doe', children: [ { id: '1.1', name: 'John doe 1.1' }, { 'id:': '1.2', 'name:': 'John doe 1.2' }, { id: '1.3', name: 'John doe 1.3', children: [ { id: '1.3.1', name: 'John doe 1.3.1' } ] } ] }, { id: '2', Name: 'Apple', children: [ { id: '2.1', name: 'Apple 2.1' }, { 'id:': '1.2', 'name:': 'Apple 1.2' } ] } ] ]
 */
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@14.0.0"></script>

免责声明:我是对象扫描的作者

于 2021-04-08T05:45:16.867 回答