JavaScript 查找具有指定子级 id 的对象在 arr 数组中的父级和子级的下标。

136 阅读1分钟

示例代码:

 var  arr= [
        {
          name: '张三',
          id: '3134154757673476096',
          children: [
            {
              name: '李四',
              id: '3134154757673476093'
            }
          ]
        },
        {
          name: '张三1',
          id: '313415475767347609611',
          children: [
            {
              name: '李四11',
              id: '313415475767347609311'
            }
          ]
        },
         {
          name: '1张三1',
          id: '1313415475767347609611111111',
          children: [
            {
              name: '李四11',
              id: '1313431547576734760931111'
            }
          ]
        },
         {
          name: '张三1',
          id: '1313415475767347609611',
          children: [
            {
              name: '李四11',
              id: '13134315475767347609311'
            }
          ]
        },
        
      ]
 //定义了三个变量:`targetId`,`parentIndex` 和 `childIndex`。`targetId` 是我们要在数组中查找的特定元素的 `id`。`parentIndex` 和 `childIndex` 分别用于存储找到的元素的父级和子级下标
let targetId = '13134315475767347609311';
let parentIndex = -1;
let childIndex = -1;
//遍历数组 `arr` 的每个元素。
for (let i = 0; i < arr.length; i++) {
// 在循环中,我们把当前元素命名为 `parent`,并检查 `parent` 是否有一个 `children` 属性。如果 `parent` 有 `children` 属性,我们就把 `children` 赋给一个新的变量 `children`。如果 `parent` 没有 `children` 属性,我们就将一个空数组赋值给 `children`。
  const parent = arr[i];
  const children = parent.children || [];
// 接下来,我们使用数组的 `findIndex` 方法在 `children` 中查找一个元素,该元素的 `id` 属性与 `targetId` 相同。如果找到了这样的元素,`findIndex` 方法会返回它在数组中的下标,否则返回 `-1`。

  const index = children.findIndex(child => child.id === targetId);
  
//如果 `findIndex` 的返回值不是 `-1`,这意味着我们找到了一个子元素的 `id` 与 `targetId` 匹配。这时,我们把当前循环的迭代变量 `i`(也就是当前父级元素在数组中的下标)赋给 `parentIndex`,把 `findIndex` 的返回值(也就是子元素在父元素的 `children` 数组中的下标)赋给 `childIndex`,break然后跳出循环。

  if (index !== -1) {
    parentIndex = i;
    childIndex = index;
    break;
  }
}
console.log('父级下标:', parentIndex);
console.log('子级下标:', childIndex);

运行结果:

image.png