JS:在映射数组时将数组压扁

  • 本文关键字:数组 JS 映射 javascript
  • 更新时间 :
  • 英文 :


如果我想要以下数据的颜色,我知道我可以做到:let colors = foo.foo.data.map(x => x.colors),它将给我一个阵列阵列:

`[[黄色,绿色,灰色,墨水,白色,柳树]]

有没有一种方法可以在映射时将其压平,而不是在映射后进行单独的迭代来压平?

let foo = { foo: {
data: [
{
name: "asdd",
age: 55, 
colors: ["red", "black"]
},
{
name: "Richard",
age: 12, 
colors: ["yellow", "green"]
},  
{
name: "Marcus",
age: 99, 
colors: ["grey", "pink"]
},
{
name: "Ian",
age: 24, 
colors: ["white", "willow"]
}, 
]
}}

有没有一种方法可以在映射时将其压平,而不是在映射后进行单独的迭代以使其变平?

是的,您可以使用.flattMap((,它将把返回的结果扁平化为一个外部结果数组,如下所示:

let foo = { foo: { data: [{ name: "asdd", age: 55, colors: ["red", "black"] }, { name: "Richard", age: 12, colors: ["yellow", "green"] }, { name: "Marcus", age: 99, colors: ["grey", "pink"] }, { name: "Ian", age: 24, colors: ["white", "willow"] }, ] } };
let colors = foo.foo.data.flatMap(x => x.colors);
console.log(colors);

您可以使用flatMap。它将创建一个包含元素的平面阵列。

foo.foo.data.flatMap(x => x.colors)

let foo = { foo: { data: [{ name: "asdd", age: 55, colors: ["red", "black"] }, { name: "Richard", age: 12, colors: ["yellow", "green"] }, { name: "Marcus", age: 99, colors: ["grey", "pink"] }, { name: "Ian", age: 24, colors: ["white", "willow"] }, ] } }
let colors = foo.foo.data.flatMap(x => x.colors)
console.log(colors)
<!-- begin snippet: js hide: false console: true babel: false -->

或者您也可以使用reduceconcat

foo.foo.data.reduce((acc, x) => acc.concat(x.colors), []);

let foo = { foo: { data: [{ name: "asdd", age: 55, colors: ["red", "black"] }, { name: "Richard", age: 12, colors: ["yellow", "green"] }, { name: "Marcus", age: 99, colors: ["grey", "pink"] }, { name: "Ian", age: 24, colors: ["white", "willow"] }, ] } }
let colors = foo.foo.data.reduce((acc, x) => acc.concat(x.colors), []);
console.log(colors)

但这是低效的,对于大型阵列应该避免。

参考flatMap

您可以使用reduce方法进行平坦化,请尝试以下方法:

let foo = { foo: {
data: [
{
name: "asdd",
age: 55, 
colors: ["red", "black"]
},
{
name: "Richard",
age: 12, 
colors: ["yellow", "green"]
},  
{
name: "Marcus",
age: 99, 
colors: ["grey", "pink"]
},
{
name: "Ian",
age: 24, 
colors: ["white", "willow"]
}, 
]
}};

let colors = foo.foo.data.map(x => x.colors).reduce((a, b) => a.concat(b), []);
console.log(colors)

没有flatMap()那么简洁,但这也适用:

let colors = [];
foo.foo.data.forEach(elmt => colors = colors.concat(elmt.colors));
console.log(colors); // Array(8) [ "red", "black", "yellow", "green", "grey", "pink", "white", "willow" ]

最新更新