将嵌套数组合并为唯一的对象



如何将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)

,但问题是,有时我的nestearray将包含另一个嵌套数组称为年龄,例如我怎样才能使它"普遍"?在某种意义上?小提琴:https://jsfiddle.net/j2v4L918/15/

看起来你在寻找笛卡尔积。下面是一个使用这个问题的答案之一的例子: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);


上面的代码片段首先使用计算属性将选项对象数组映射到单个对象数组:
[
{ 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来合并单个对象,并确保将它们赋值为空对象,并使用扩展语法(…)来扩展对象的子数组。

Object.assign({}, ...[{ gender: 'male' }, { subject: 'spanish' }])
//            ^^ assign into empty object to avoid reference problems

最新更新