我有一个纯 JavaScript 对象数组,例如
const drawings = [
{
name: "Foo",
category: "widget"
},
{
name: "Bar",
category: "widget"
},
{
name: "Bar",
category: "fidget"
},
]
等,名称和类别都有重复。我最终想要得到的本质上是一个对象列表(这是为了满足第 3 方库的接口(interface)),其中每个对象代表一个名称,然后对于每个类别都有一个属性,要么是 true 要么是 false,取决于原始列表。因此,对于示例,输出将是:
const output = [
{
name: "Foo",
widget: true,
fidget: false
},
{
{
name: "Bar",
widget: true,
fidget: true
},
]
最佳答案
我会首先检查并创建一个类别对象,其中类别作为键,默认值为 false
。
然后您可以将它分配给每个对象,并在您完成时将正确的键设置为 true。
const drawings = [{name: "Foo",category: "widget"},{name: "Bar",category: "widget"},{name: "Bar",category: "fidget"},]
// make category object where everything is false
let category_obj = drawings.reduce((a, item) => (a[item.category] = false, a), {})
let output = drawings.reduce((a, {name, category}) => {
// assign cat
if (!a.hasOwnProperty(name)) a[name] = Object.assign({}, {name}, category_obj)
// set to true if the correct category
a[name][category] = true
return a
}, {})
// the above makes an object, but you only want the array of values
console.log(Object.values(output))
关于javascript - 从对象数组构建邻接矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51370809/