如何根据嵌套数组中的值将nestedArray 转换为对象数组? 这是一个例子:
const nestedArray = [{
id: "Degree",
options: ["HighSchool", "Undergraduate", "Bachelor", "Master", "Doctor"]
}, {
id: "gender",
options: ["male", "female"]
}]
const arrayOfObjects = []
nestedArray[0].options.map((degree) => {
nestedArray[1].options.map((gender) => {
let currObject = {}
currObject[nestedArray[0].id] = degree
currObject[nestedArray[1].id] = gender
arrayOfObjects.push(currObject)
})
})
console.log(arrayOfObjects)
但问题是有时我的nestedArray将包含另一个名为age的嵌套数组 我怎样才能使这个“普遍”在某种意义上? fiddle :https://jsfiddle.net/j2v4L918/15/
最佳答案
您似乎正在寻找 cartesian product 。以下是使用此问题的答案之一的示例:Cartesian product of multiple arrays in JavaScript .
/**
* @see https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript
*/
const cartesian = (...a) => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())));
const nestedArray = [
{ id: "Degree", options: ["HighSchool", "Undergraduate", "Bachelor", "Master", "Doctor"] },
{ id: "gender", options: ["male", "female"] },
{ id: "subject", options: ["spanish", "geometry"] }
];
const arrayOfEntries = nestedArray.map(({ id, options }) => options.map(option => ({ [id]: option })));
const cartesianProduct = cartesian(...arrayOfEntries);
const arrayOfObjects = cartesianProduct.map(arr => Object.assign({}, ...arr))
console.log(arrayOfObjects);
说明
上面的代码片段首先使用 computed properties 将选项对象数组映射到单个对象数组。 :
[
{ id: "gender", options: ["male", "female"] },
{ id: "subject", options: ["spanish", "geometry"] }
];
// mapped to individual objects: {[id]: option}
[
[ { gender: 'male' }, { gender: 'female' } ],
[ { subject: 'spanish' }, { subject: 'geometry' } ]
]
然后计算这些条目的笛卡尔积:
// cartesian product of individual objects
[
[ { gender: 'male' }, { subject: 'spanish' } ],
[ { gender: 'male' }, { subject: 'geometry' } ],
[ { gender: 'female' }, { subject: 'spanish' } ],
[ { gender: 'female' }, { subject: 'geometry' } ]
]
最后,我们 map()
对该数组进行映射,并将各个对象传递给 Object.assign
来合并它们。确保分配给一个空对象,并使用 spread syntax (...)扩展对象的子数组。
Object.assign({}, ...[{ gender: 'male' }, { subject: 'spanish' }])
// ^^ assign into empty object to avoid reference problems
关于javascript - 将嵌套数组合并为唯一对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71916506/