我有一个普通的JavaScript对象数组,例如
const drawings = [
{
name: "Foo",
category: "widget"
},
{
name: "Bar",
category: "widget"
},
{
name: "Bar",
category: "fidget"
},
]
etc,其中名称和类别均重复。我最终想要得到的实际上是一个对象列表(这是第3方库的接口),其中每个对象代表一个名称,然后对于每个类别都有一个true或false的属性,取决于原始列表。因此,对于该示例,输出为:
const output = [
{
name: "Foo",
widget: true,
fidget: false
},
{
{
name: "Bar",
widget: true,
fidget: true
},
]
答案 0 :(得分:1)
首先,我将以类别为键,默认值为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))
答案 1 :(得分:0)
如果您已经知道类别或按照建议进行推断,则可以像这样使用Array.reduce():
drawings.reduce(function(acc, curr) {
if (!acc.some(elt => elt.name === curr.name)) {
acc.push({name: curr.name, widget: false, fidget: false})
}
const i = acc.findIndex(elt => elt.name === curr.name)
acc[i][curr.category] = true
return acc
}, [])