Javascript 对对象属性的重复数组进行计数以生成新数组
我有这个对象数组Javascript 对对象属性的重复数组进行计数以生成新数组,javascript,arrays,reactjs,object,ecmascript-6,Javascript,Arrays,Reactjs,Object,Ecmascript 6,我有这个对象数组 [{ tag: 'james' }, { tag: 'james' }, { tag: 'john' } ] 如何计算并生成如下所示的新数组 [{ tag: 'james', count: 2 }, { tag: 'john', count: 1 }] 我尝试使用reduce生成的对象而不是对象数组 const arr=[{tag:'james'},{tag:'james'},{tag:'john'}]; 让ne
[{
tag: 'james'
},
{
tag: 'james'
},
{
tag: 'john'
}
]
如何计算并生成如下所示的新数组
[{
tag: 'james',
count: 2
}, {
tag: 'john',
count: 1
}]
我尝试使用reduce生成的对象而不是对象数组
const arr=[{tag:'james'},{tag:'james'},{tag:'john'}];
让newArr=arr.reduce((累计,arr)=>{
累计[arr.tag]=++acum[arr.tag]| 1
返回累计
}, {})
console.log(newArr)
如果对象不存在,则进行第一次测试-如果不存在,则创建一个。然后添加到蓄能器中。还请注意,您需要一个数组,因此对累加器值使用[]
而不是{}
:
const数据=[{
标签:“詹姆斯”
},
{
标签:“詹姆斯”
},
{
标签:“约翰”
}
];
const group=data.reduce((acc,{tag})=>{
如果(!acc.some(e=>e.tag==tag)){
acc.push({tag,count:0});
}
acc.find(e=>e.tag==tag).count++;
返回acc;
}, []);
控制台日志(分组)代码>
.as控制台包装{max height:100%!important;top:auto;}
创建一个对象而不是一个数字,最后使用方法从对象中获取这些值
let arr=[{tag:'james'},{tag:'james'},{tag:'john'}]
让res=对象值(arr.reduce((acum,o)=>{
accum[o.tag]=accum[o.tag]|{…o,计数:0}
累计[o.tag].count++;
返回累计
}, {}))
log(res)
您就快到了,但是您需要从对象中取出键和值并构建一个新数组
var数组=[{tag:'jane'},{tag:'jane'},{tag:'john'}],
结果=对象
.参赛作品(
array.reduce((acum,{tag})=>{
累计[标记]=(累计[标记]| | 0)+1;
返回累计;
}, {}))
.map(([tag,count])=>({tag,count}));
控制台日志(结果)代码>
。作为控制台包装{max height:100%!important;top:0;}
更简单的代码是:
const arr=[{
标签:“詹姆斯”
},
{
标签:“詹姆斯”
},
{
标签:“约翰”
},
{
标签:“刘易斯”
},
{
标签:“约翰”
}
]
常数计数=arr.reduce((acc,cv)=>{
const val=acc.find(t=>t.tag==cv.tag)
if(val){
瓦尔伯爵++
附件推送(val)
返回acc
}
cv.count=1
加速推力(cv)
返回acc
}, [])
console.log(counts)
你的直觉很好,而且非常接近;我给你一个更一般的答案
const groupTags = data => field => Object.values(data.reduce((acc, o) =>
({...acc,
[o[field]]: {
[field]: o[field],
count: acc[o[field]] ? acc[o[field]].count + 1 : 1
}
}), {}))
你可以像这样使用它
groupTags(data)("tag")
为什么要看地图?来自Balan的一个似乎更简单let res=Object.values(arr.reduce((acum,o)=>{acum[o.tag]=acum[o.tag]|{…o,count:0}acum[o.tag].count++;return acum},{}))
我的解决方案将开销保持得很小(和抽象),并构建最终的对象,其中,指定的代码直接构建最终对象作为对象的值。这看起来像是品味的问题。
groupTags(data)("tag")
//simple approach using forEach method
let lists = [{tag: 'james'},{tag: 'james'},{tag: 'john'}];
const finalOutput = [];
const tempStore = {};
lists.forEach((list) => {
tempStore[list.tag] = (tempStore[list.tag] == undefined) ? 1: tempStore[list.tag]+1;
const index = finalOutput.findIndex(e => e.tag == list.tag);
if(index > -1) {
finalOutput[index] = {tag: list.tag, count: tempStore[list.tag]}
}
else
finalOutput.push({tag: list.tag, count: tempStore[list.tag]})
});
console.log(finalOutput);