使用javascript为相同的ID添加JSON数组元素

时间:2018-09-21 05:24:41

标签: javascript arrays json

我将数据解析为变量

var Mydata = [
  {
    count: 4,
    min: 0,
    max: 0,
    mean: 0,
    ID: 1
  },
  {
    count: 12,
    min: 0,
    max: 0,
    mean: 0,
    ID: 2
  },
  {
    count: 9,
    min: 0,
    max: 0,
    mean: 0,
    ID: 3
  },
  {
    count: 4,
    min: 0,
    max: 0,
    mean: 0,
    ID: 1
  }
];

如果“ ID”相同,我想添加数组元素

预期:

Mydatanew = [
  {
    count: 8,
    min: 0,
    max: 0,
    mean: 0,
    ID: 1
  },
  {
    count: 12,
    min: 0,
    max: 0,
    mean: 0,
    ID: 2
  },
  {
    count: 9,
    min: 0,
    max: 0,
    mean: 0,
    ID: 3
  }
];

6 个答案:

答案 0 :(得分:0)

您可以这样做。

lodashJS> uniqBy !!

_.uniqBy([
    {count: 4, min: 0, max: 0, mean: 0, ID: 1},
    {count: 12, min: 0, max: 0, mean: 0, ID: 2},
    {count: 9, min: 0, max: 0, mean: 0, ID: 3},
    {count: 4, min: 0, max: 0, mean: 0, ID: 1}
], 'ID');

参考:https://lodash.com/docs/4.17.10#uniqBy


但是uniqBy可以覆盖以前的值...只需阻止添加新项...

如果要将最后一个元素设为默认值,请按desc排序。

答案 1 :(得分:0)

var Mydata = [
{count: 4, min: 0, max: 0, mean: 0, ID: 1},
{count: 4, min: 0, max: 0, mean: 0, ID: 1},
{count: 12, min: 0, max: 0, mean: 0, ID: 2},
{count: 9, min: 0, max: 0, mean: 0, ID: 3},
{count: 4, min: 0, max: 0, mean: 0, ID: 1}
];

var Mydata = Mydata.reduce(function(obj,val){
 obj[val.ID]?obj[val.ID].count += val.count:obj[val.ID] = val;
return obj;
},{});

Mydata = Object.values(Mydata);

console.log(Mydata);

答案 2 :(得分:0)

var Mydata = [{count: 4, min: 0, max: 0, mean: 0, ID: 1},
{count: 12, min: 0, max: 0, mean: 0, ID: 2},
{count: 9, min: 0, max: 0, mean: 0, ID: 3},
{count: 4, min: 0, max: 0, mean: 0, ID: 1}];

var reducer = Mydata.reduce((acc,item)=>{
	if(acc[item.ID]){
		//add the items
		acc[item.ID].count += item.count;
	}
	else{
		acc[item.ID] = item;
	}
	return acc;

},{});

var newMyData = Object.values(reducer);
console.log(newMyData);

答案 3 :(得分:0)

@Nishant几乎正确,但是我发现您需要一个if语句而不是三元运算符:

已编辑(感谢@aytee提供了防止原始数据变异的提示!):

var Mydata = [{count: 4, min: 0, max: 0, mean: 0, ID:1},
{count: 12, min: 0, max: 0, mean: 0, ID: 2},
{count: 9, min: 0, max: 0, mean: 0, ID: 3},
{count: 4, min: 0, max: 0, mean: 0, ID: 1}];

var reformedData=Object.values(Mydata.reduce(function(obj,val){
 if (obj[val.ID]) obj[val.ID].count +=val.count; 
 else obj[val.ID] = Object.assign({},val); // create an independent "copy with same values"
return obj;
},{}));
console.log(reformedData); // result: the consolidated data object
console.log(Mydata);       // still there and unchanged: the original data object

答案 4 :(得分:0)

var Mydata = [{
    count: 4,
    min: 0,
    max: 0,
    mean: 0,
    ID: 1
  },
  {
    count: 12,
    min: 0,
    max: 0,
    mean: 0,
    ID: 2
  },
  {
    count: 9,
    min: 0,
    max: 0,
    mean: 0,
    ID: 3
  },
  {
    count: 4,
    min: 0,
    max: 0,
    mean: 0,
    ID: 1
  }
];


var result = {}
var t_key = {
  'count': 1,
  'min': 1,
  'max': 1,
  'mean': 1
}
Mydata.forEach(function(f) {
  if (f['ID'] in result) {
    for (var key in t_key) {
      if (key == 'count') {
        result[f['ID']][key] = (result[f['ID']][key] + f[key])
      } else if (key == 'min') {
        if (f[key] < result[f['ID']][key]) {
          result[f['ID']][key] = f[key]
        }
      } else if (key == 'max') {
        if (f[key] > result[f['ID']][key]) {
          result[f['ID']][key] = f[key]
        }
      } else if (key == 'mean') {
        result[f['ID']][key] = (result[f['ID']][key] + f[key])
      }
    }
  } else {
    result[f['ID']] = f
  }
})
console.log('final_result', Object.values(result))

var Mydata = [{
    count: 4,
    min: 0,
    max: 0,
    mean: 0,
    ID: 1
  },
  {
    count: 12,
    min: 0,
    max: 0,
    mean: 0,
    ID: 2
  },
  {
    count: 9,
    min: 0,
    max: 0,
    mean: 0,
    ID: 3
  },
  {
    count: 4,
    min: 0,
    max: 0,
    mean: 0,
    ID: 1
  }
];


var result = {}
var t_key = {
  'count': 1,
  
}
Mydata.forEach(function(f) {
  if (f['ID'] in result) {
    for (var key in t_key) {
      result[f['ID']][key] = (result[f['ID']][key] + f[key])
    }
  } else {
    result[f['ID']] = f
  }
})
console.log( Object.values(result))

答案 5 :(得分:0)

const MyData = [
  { count: 4, min: 0, max: 0, mean: 0, ID: 1 },
  { count: 12, min: 0, max: 0, mean: 0, ID: 2 },
  { count: 9, min: 0, max: 0, mean: 0, ID: 3 }
];

const NewDataAdd = { count: 100, min: 1, max: 2, mean: 0, ID: 6 };
const NewDataRewrite = { count: 100, min: 1, max: 2, mean: 0, ID: 1 };

const updateData = (data, update) => {
  let isNew = true;

  data.map(item => {
    // if object is allready in array, overwrites it
    if (item.ID === update.ID) {
       isNew = false;
       return update
    }
  })
  
  // otherwise adds it to array
  if (isNew) return [ ...data, update];

  return data;
}

const test1 = updateData(MyData, NewDataAdd);
const test2 = updateData(MyData, NewDataRewrite);// takes array and an object

console.log(test1);
console.log(test2);