如何从对象数组中提取所有groups子数组元素并合并为新数组?
如何从对象数组中提取并合并所有嵌套的groups数组对象?
你当前代码里用find方法只能拿到第一个包含groups属性的对象,无法实现合并所有嵌套groups数组的需求。可以通过以下两种方式实现目标:
方法一:使用flatMap(简洁推荐)
flatMap可以先映射每个元素的groups,再自动扁平化数组,同时过滤掉非数组类型的groups:
const GroupData = mydata.flatMap(item => { // 仅当groups是数组时返回其内容,否则返回空数组 return Array.isArray(item.groups) ? item.groups : []; });
方法二:使用reduce(兼容性更广)
如果需要兼容不支持flatMap的环境,可以用reduce手动累加:
const GroupData = mydata.reduce((result, item) => { // 判断groups是否为数组,是的话就展开添加到结果数组 if (Array.isArray(item.groups)) { result.push(...item.groups); } return result; }, []);
执行上述代码后,GroupData就会得到你期望的结果:
[ { id: "679d8044", name: "group 3" }, { id: "b9342eb8", name: "group 1" } ]
内容的提问来源于stack exchange,提问作者walee
相关产品推荐
相关产品推荐

