展平Javascript数组 [英] Flatten Javascript array
本文介绍了展平Javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的对象数组:
I have an array of objects like this:
let list = [
{
'items': [
'item 1',
'item 2'
]
},
{
'items': [
'item 3'
]
}
]
我想像这样从这个对象中展平数组:
and I want flatten the arrays from this object like this:
['item 1','item 2','item 3']
此输出应使用哪个JavaScript函数?
Which JavaScript function should I use for this output?
我尝试过使用map函数:
I have tried with the map function:
list.map(i => i.items)
但是我得到了以下输出:
but I got this output:
[["item 1","item 2"],["item 3"]]
注意:我正在寻找任何现有功能或包装在功能中的答案,以便我可以调用功能-而不是自己编写循环.
NOTE : I am looking for any existing function or an answer that is wrapped in a function so I can just call a function - not write the loop out myself.
推荐答案
You can flat the map()
result using Array.prototype.flatMap()
:
flatMap()
方法首先使用映射函数映射每个元素,然后将结果展平为新数组.
The
flatMap()
method first maps each element using a mapping function, then flattens the result into a new array.
let list = [
{
'items': [
'item 1',
'item 2'
]
},
{
'items': [
'item 3'
]
}
]
list = list.flatMap(i => i.items);
console.log(list);
这篇关于展平Javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文