数组里有children,如何获取数组中所有对象某个key对应的值,组成新的值存在数组里面

1,在实际开发中我们会遇到数组中包含chidren的数组,我们如果想要获取数组中某个指定的key对应值的组成新的key和value的时候,这时候我们改怎么简单方便的操作呢?

1:如何获取里面所有的id值,包括children里的
[
  {
       id: 1,
       age: 23,
       name: '测试1',
       children: [
         {
              id: 2,
              age: 24,
              name: '测试11',
              children: [
           {
               id: 3,
               age: 244,
               name: '测试111'
            },
        ]
         }
       ]
   },
   {
       id: 4,
       age: 26,
       name: '测试2',
       children: [],
   }
]
方法一…运算符使用解决:
let a = [
  {
       id: 1,
       age: 23,
       name: '测试1',
       children: [
         {
              id: 2,
              age: 24,
              name: '测试11',
              children: [
           {
               id: 3,
               age: 244,
               name: '测试111'
            },
        ]
         }
       ]
   },
   {
       id: 4,
       age: 26,
       name: '测试2',
       children: [],
   }
]

// (1)
function func(arr){
  return arr.reduce((a, b) => {
    let res = [...a,b.id];
    if (b.children) res = [...res, ...func(b.children)];
    return res;
  }, []);
}

// (2)
function func(arr) {
   return arr.reduce((a, b) => {
     return b.children
       ? [...a, b.id, ...func(b.children)]
       : [...a, b.id];
   }, []);
 }
console.log(func(a))  
// 结果: [1,2,3,4]
方法二: 使用for循环遍历,然后在递归
// (1)
let arr= [
   { id: 1, children: [{ id: 2 },{ id: 3 }] },
   { id: 4, children: [] }
 ];
// 获取对应id
const getIds = function(arr) {
const res = arr.reduce((prev, next) => {
	 if (next.id) prev.push(next.id);
	 if (next.children && next.children.length) return prev.concat(getIds(next.children));
	    return prev;
	    }, []);
	    return res;
  };
 const res = getIds(arr);
 console.log(res);
 
 // 获取对应需要的key
 function getKeys(list, key) {
    return list.reduce((res, v) => {
        if(v.children && v.children.length) res = res.concat(getKeys(v.children,key))
        res.push(v[key]);
        return res;
    }, [])
}
console.log(getKeys(arr, 'id'))

// (2)
const getIdsArry = (arr) => {
  const ans = [];

  const dfs = (root, ans) => {
    let neighbor;
    if (Array.isArray(root)) {
      neighbor = root;
    } else {
      ans.push(root.id);
      neighbor = root.children;
    }

    if (!neighbor) return;

    for (let i = 0; i < neighbor.length; ++i) {
      dfs(neighbor[i], ans);
    }
  };

  dfs(arr, ans);

  return ans;
};
console.log(getIds (arr))
2:跟上面借结构一样,获取children里面对应的id [2,3]
let a = [
   { id: 1, children: [{ id: 2 },{ id: 3 }] },
   { id: 4, children: [] }
 ];
 function func(arr) {
   return arr.reduce((a, b) => {
     return b.children ? [...a, ...func(b.children)] : [...a, b.id];
   }, []);
 }
 console.log(func(a));
 // 结果  [2,3]
3,组成新的值存放数组里面

在这里插入图片描述

var aa = [
  {
        id: 1,
        age: 23,
        name: '测试1',
        children: [
          {
               id: 2,
               age: 24,
               name: '测试11',
               children: [
	           {
                id: 3,
                age: 244,
                name: '测试111'
	            },
	        ]
          }
        ]
    },
    {
        id: 4,
        age: 26,
        name: '测试2',
        children: [],
    }
    ]
for (var itemproject = 0; itemproject < aa.length; itemproject++) {
     if (aa[itemproject].children && aa[itemproject].children.length > 0) {
        aa[itemproject].selectedFields = getidarry(aa[itemproject].children)
      } else {
        aa[itemproject].selectedFields = []
      }
}
function getidarry (arr) {
  	  return arr.reduce((a, b) => {
	   let res = [...a,b.id];
	   if (b.children) res = [...res, ...getidarry(b.children)];
	   return res;
	 }, []);
}
console.log('新数组', aa)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果您想要递归地删除数组中具有特定键的对象元素,您可以使用以下 JavaScript 代码示例: ```javascript function recursiveDelete(arr, key, value) { for (let i = 0; i < arr.length; i++) { if (arr[i].hasOwnProperty(key) && arr[i][key] === value) { arr.splice(i, 1); i--; // 由于删除了一个元素,需要将索引回退一位 } else if (Array.isArray(arr[i])) { recursiveDelete(arr[i], key, value); // 递归调用,处理嵌套数组 } else if (typeof arr[i] === 'object') { recursiveDelete(Object.values(arr[i]), key, value); // 递归调用,处理嵌套对象 } } } // 示例用法 const data = [ { id: 1, name: 'John', children: [] }, { id: 2, name: 'Jane', children: [ { id: 3, name: 'Bob', children: [] }, { id: 4, name: 'Alice', children: [] } ] }, { id: 5, name: 'Mike', children: [] } ]; recursiveDelete(data, 'id', 3); console.log(data); ``` 在上面的示例中,我们定义了一个名为 `recursiveDelete` 的递归函数,它接受三个参数:要处理的数组、要删除的键和要匹配的。函数遍历数组的每个元素,如果元素具有指定的键且键对应等于给定的,使用 `splice` 方法将其从数组中删除。如果元素是嵌套的数组,则递归调用 `recursiveDelete` 函数处理嵌套数组。如果元素是对象,则使用 `Object.values` 方法转换为数组,并再次递归调用 `recursiveDelete` 函数处理嵌套对象。 请注意,上述示例会直接修改原始数组。如果您希望保留原始数组不变,可以在函数内部创建一个的副本进行处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值