javascript - 嵌套数组Javascript中的Flattern对象
问题描述
我有一个包含对象的数组数组,想要获取某个键的值并将其作为一个大数组返回,尝试了嵌套映射,但它返回多个数组而不是单个数组。
const items = [
{
id: 1,
sub_items: [
{
id: 1
},
{
id: 2
},
{
id: 3
}
]
},
{
id: 2,
sub_items: [
{
id: 4
},
{
id: 5
},
{
id: 6
}
]
}
]
const subItemIDs = items.map( (item) =>
item.sub_items.map( (subItem) => subItem.id )
)
console.log(subItemIDs);
预期产出
[1, 2, 3, 4, 5, 6]
实际输出
[ [1,2,3], [4,5,6] ]
解决方案
您可以使用arrays.flat()
. 一旦问题中提到输出,我可以提供更具体的代码
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]
推荐阅读
- kubernetes - 将文件从k8s中的容器管道传输到本地机器,编辑并复制回k8s中的容器?
- c++ - 'operator sockaddr *()' 在这里是什么意思?
- pandas-profiling - pandas-profiling 如何确定使用哪种关联方法在报告中生成关联警告?你能显示相关的方法吗?
- javascript - 浮点数据类型在javascript中更改为int
- javascript - 如何向 Google 表格客户端添加访问和刷新令牌?
- javascript - 如何在“getElementById”函数中放置for循环?
- php - 如何在 WP Admin 中过滤分类术语?
- jsp - 在 tomcat 中找不到 JSP 页面链接,但它实际上存在
- javascript - 将 .text() 转换为 .val()
- excel - 使用以下代码后如何进行复制/粘贴?