我有以下带有嵌套数组的数组:
const options = [
[
{
label: "Blue",
option_id: "1"
},
{
label: "Small",
option_id: "2"
}
],
[
{
label: "Red",
option_id: "1"
},
{
label: "Large",
option_id: "2"
}
]
];
我想从每一对中创建一个对象数组,例如:
[
{
label: ”Blue Small“,
option_id: [1,2]
},
...
]
编辑:感谢大家的精彩回答
最佳答案
在 options
数组上使用 .map
,并将每个子数组reduce
为一个对象:
const options = [
[
{
label: "Blue",
option_id: "1"
},
{
label: "Small",
option_id: "2"
}
],
[
{
label: "Red",
option_id: "1"
},
{
label: "Large",
option_id: "2"
}
]
];
const result = options.map(arr =>
arr.reduce(
(a, { label, option_id }) => {
a.label += (a.label ? ' ' : '') + label;
a.option_id.push(option_id);
return a;
},
{ label: '', option_id: [] }
)
);
console.log(result);
关于javascript - 从包含对象的嵌套数组的数组创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55039704/