我有这个对象数组
[{
tag: 'james'
},
{
tag: 'james'
},
{
tag: 'john'
}
]
如何计算并生成如下所示的新数组?
[{
tag: 'james',
count: 2
}, {
tag: 'john',
count: 1
}]
我尝试使用 reduce 生成的对象而不是对象数组。
const arr = [{tag: 'james'},{tag: 'james'},{tag: 'john'}];
let newArr = arr.reduce((accum, arr) => {
accum[arr.tag] = ++accum[arr.tag] || 1
return accum
}, {})
console.log(newArr)
最佳答案
创建一个对象而不是数字,最后使用 Object.values
方法从对象中获取这些值。
// just extract values from the object as an array
let res = Object.values(arr.reduce((accum, o) => {
// initialize object if not defined already
accum[o.tag] = accum[o.tag] || { ...o, count: 0 }
// increment count property
accum[o.tag].count++;
return accum
}, {}))
let arr = [{tag: 'james'},{tag: 'james'},{tag: 'john'}]
let res = Object.values(arr.reduce((accum, o) => {
accum[o.tag] = accum[o.tag] || { ...o, count: 0 }
accum[o.tag].count++;
return accum
}, {}))
console.log(res)
您甚至可以通过使用用于对象/索引引用的附加变量来直接创建数组。
// an object for keeping reference
let ref = {};
let res = arr.reduce((accum, o) => {
// check reference already defined, if not define refernece and push to the array
ref[o.tag] || accum.push(ref[o.tag] = { ...o, count: 0 })
// update count using the refernece keeped in the object
ref[o.tag].count++;
return accum
}, []);
let arr = [{tag: 'james'},{tag: 'james'},{tag: 'john'}]
let ref = {};
let res = arr.reduce((accum, o) => {
ref[o.tag] || accum.push(ref[o.tag] = { ...o, count: 0 })
ref[o.tag].count++;
return accum
}, []);
console.log(res)
关于javascript - 计算对象属性的重复数组以生成新数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55469468/