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

标签 javascript node.js

如何根据嵌套数组中的值将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/

相关文章:

node.js - 转换为数字失败的值 - GraphQL

javascript - 无法在 Node js 中使用 ecdsa 模块进行签名

javascript - 当处理请求发布ajax时,如何禁用此表单中的表单(用户无法检查、填充文本、选择下拉列表等)?

javascript - HtmlUnit 获取编码错误的字符串

javascript - Express-Session 中的对象方法

javascript - 验证 Facebook X-Hub-签名

javascript - 无法使用 iOS 向下滚动 100% 高度部分

JavaScript 对象检测 : dot syntax versus 'in' keyword

javascript - node.js 将 http 响应写入流

node.js - 播放/暂停音频流 NodeJs