我有1个对象数组,并且想要遍历其中的对象。因此,如果找到重复的名称条目,我必须添加计数器值,并且应该将其合并。对象的最终数组必须具有唯一的条目。
ObjectA =
[
{name: 'Voice', counter: 1},
{name: 'tele', counter: 1},
{name: 'equip', counter: 1},
{name: 'equip', counter: 2},
{name: 'Voice', counter: 1}
]
结果应为:-
ObjectB =
[
{name: 'Voice', counter: 2},
{name: 'tele', counter: 1},
{name: 'equip', counter: 3}
]
答案 0 :(得分:0)
您可以按照以下逻辑使用 array.reduce
。
DEMO
let data = [{name: 'Voice', counter: 1},
{name: 'tele', counter: 1},
{name: 'equip', counter: 1},
{name: 'equip', counter: 2},
{name: 'Voice', counter: 1}]
var result = [];
data.reduce(function (res, value) {
if (!res[value.name]) {
res[value.name] = {
name: value.name,
counter: 0
};
result.push(res[value.name])
}
res[value.name].counter += value.counter
return res;
}, {});
console.log(result)
答案 1 :(得分:0)
您可以取Map
并求和所有counter
的值,并按name
分组。
var data = [{ name: 'Voice', counter: 1 }, { name: 'tele', counter: 1 }, { name: 'equip', counter: 1 }, { name: 'equip', counter: 2 }, { name: 'Voice', counter: 1 }],
unique = Array.from(
data.reduce((m, { name, counter }) => m.set(name, (m.get(name) || 0) + counter), new Map),
([name, counter]) => ({ name, counter })
);
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
尝试这种方法:
const arr = [
{name: 'Voice', counter: 1},
{name: 'tele', counter: 1},
{name: 'equip', counter: 1},
{name: 'equip', counter: 2},
{name: 'Voice', counter: 1}
];
const resultObj = arr.reduce((acc, item) => {
acc[item.name] = (acc[item.name] || 0) + item.counter;
return acc;
}, {})
const resultArr = Object.entries(resultObj).map(entry => ({
name: entry[0],
counter: entry[1]
}))
document.body.innerHTML = `<pre>${JSON.stringify(resultArr, null, 2)}</pre>`
答案 3 :(得分:0)
您可以使用reduce将列表中具有相同name
的对象分组。稍后,如果找到具有相同名称的对象,则将counter
增加,否则该对象将被推入数组。
var arr = [{name: 'Voice', counter: 1},
{name: 'tele', counter: 1},
{name: 'equip', counter: 1},
{name: 'equip', counter: 2},
{name: 'Voice', counter: 1}];
var newArray = arr.reduce((acc, item)=>{
var element = acc.find(obj => obj['name'] === item['name']);
if(element){
element['counter'] = element['counter'] + 1;
}else{
acc.push(item);
}
return acc;
}, []);
console.log(newArray);
答案 4 :(得分:0)
您可以使用lodash减少功能
let data = [{name: 'Voice', counter: 1},
{name: 'tele', counter: 1},
{name: 'equip', counter: 1},
{name: 'equip', counter: 2},
{name: 'Voice', counter: 1}];
data = _.reduce(data, (arr, n)=> {
const index = _.findIndex(arr,{name: n.name});
if(index !== -1){
arr[index].counter += 1;
} else {
arr.push(n);
}
return arr;
},[]);
console.log(data);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>