在javascript中查找对象数组中的重复项 [英] finding duplicates in array of objects javascript

查看:116
本文介绍了在javascript中查找对象数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的对象数组:

I have an array of objects that looks like the following:

            {value: 20, color: 'F88C00'},
            {value: 40, color: 'D8605F'},
            {value: 20, color: '72C380'},
            {value: 20, color: '2C7282'},
            {value: 20, color: '72C380'}

我想使用javascript / jquery循环遍历它们以检查颜色列中是否有任何重复,如果有重复,则此处'72C380'出现两次。然后应该只有一个条目,但它们的值应该相加。

I want to use javascript/jquery to loop through them to check if there are any duplicates in the color column, and if there are duplicates, here '72C380' occurs twice. Then there should be only one entry but their values should be summed.

所需的输出:

            {value: 20, color: 'F88C00'},
            {value: 40, color: 'D8605F'},
            **{value: 40, color: '72C380'},**
            {value: 20, color: '2C7282'}

我知道怎么做在python中,但不是JS

I know how to do that in python, but not JS

推荐答案

你可以使用这样的临时地图

You can use a temp map like this

var array = [{
    value: 20,
    color: 'F88C00'
}, {
    value: 40,
    color: 'D8605F'
}, {
    value: 20,
    color: '72C380'
}, {
    value: 20,
    color: '2C7282'
}, {
    value: 20,
    color: '72C380'
}];

var op = [],
    map = {}, it, item;
for (var i = 0; i < array.length; i++) {
    it = array[i];
    item = map[it.color];
    if (item) {
        item.value += it.value;
    } else {
        map[it.color] = item = {
            value: it.value,
            color: it.color
        };
        op.push(item);
    }
}
console.log(op)

演示:小提琴

这篇关于在javascript中查找对象数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆