检查jquery对象数组是否匹配键。 + =如果匹配则为值,如果不匹配则推送新对象

时间:2017-08-07 17:12:00

标签: javascript jquery arrays

用户将填写一个数据表,然后我需要迭代表,将其分组,并确保每个组== 100。

我的计划是遍历表行,制作key:value对象,检查数组是否匹配键。如果键匹配,则将值添加到现有数组对象。如果不匹配,请按下新项目。

假设这个数组:

var gidArr =
[
    {   
        gid: '123',
        ratio: '20'
    },
    {   
        gid: '123',
        ratio: '40'
    },
    {   
        gid: '432',
        ratio: '50'
    },

]  

结果应该是:

{ gid:123, ratio:60 },
{ gid:432, ration: 50}

我尝试过几件事:

function GIDRatio(gid, ratio) {
    this.gid = gid;
    this.ratio = parseFloat(ratio);
}
        var item = new GIDRatio(gid, ratio);

1:
        if(gid in gidArr) {
            gidArr.ratio += item.ratio;
        } else {
            gidArr.push(item);
        }

2:

    $.each(gidArr, function(i, v) {
        if(v.gid === item.gid) {
             v.ratio += item.ratio;
        } else {
             gisArr.push(item);
        }
    })

小提琴:https://jsfiddle.net/8vw4eehs/11/

3 个答案:

答案 0 :(得分:2)

您可以使用Array.reduce方法将原始数组转换为新结构。

reduce功能中,只需检查acc是否accumulated arraygid已可用。如果没有,那么推入阵列。如果是,则计算ratio的总和并更新ratio



var gidArr =
[
    {   
        gid: '123',
        ratio: '20'
    },
    {   
        gid: '123',
        ratio: '40'
    },
    {   
        gid: '432',
        ratio: '50'
    },

];

const newArr = gidArr.reduce((acc, cur) => {
  if(acc.some(x => x.gid === cur.gid)) {
    acc.map(x => {
      if(x.gid === cur.gid) {
        x.ratio = (+x.ratio) + (+cur.ratio);
      }
      return x;
    });
  } else {
    acc.push(cur);
  }
  return acc;
},[])

console.log(newArr);




答案 1 :(得分:0)

使用Array.prototype.reduce转换为3.3 ------------GET------------------- names vector index is 0 double property vector index is 0 Property Name are equal to 3.3 Current value = 3.3 ,然后累积hashtable - 请参阅下面的演示:



ratio




答案 2 :(得分:0)

var gidArr = [
  {gid: '123', ratio: '20'}, 
  {gid: '123', ratio: '40'}, 
  {gid: '432', ratio: '50'},
  {gid: '123', ratio: '40'}
];

/* Creating an array of objects */ 

var obj = gidArr.reduce((a,b) => (a[b.gid] = b.gid in a ? a[b.gid]+(+b.ratio):(+b.ratio), a),{});
var arr = Object.keys(obj).map(x => ({[x]:obj[x]}));

console.log(arr, "\n---------------------------")

/* Filtering based on values being 100 */

var result = arr.filter( o => Object.values(o)[0] === 100 );
console.log(result)
.as-console-wrapper {max-height: 100%!important; top: 0}