2017-05-31 57 views
0

对象的集合是否有javascipt的或Lodash方法的对象的此集合结合:结合基于多个属性

[ 
{ 
    typeId: 'random1' 
    catId: 'random2' 
    val: '2' 
}, 
{ 
    typeId: 'random1' 
    catId: 'random2' 
    val: '3' 
}, 
{ 
    typeId: 'random1' 
    catId: 'random4' 
    val: '1' 
} 
] 

到这一个,与独特TYPEID-CATID对和数值的每个对象值总结如下:

[ 
{ 
    typeId: 'random1' 
    catId: 'random2' 
    val: '5' 
}, 
{ 
    typeId: 'random1' 
    catId: 'random4' 
    val: '1' 
} 
] 
+0

那么,你可能会使用'_.mergeWith(object,sources,customizer)',但这听起来不像一个非常复杂的函数从头开始写。我怀疑这是自动的,特别是当这些数字是字符串时。 – Roope

+0

看起来有点过于具体,图书馆不能立即处理。 –

回答

1

首先创建一个对象,跟踪类似对象的总值,然后将它们处理成最终输出格式。事情是这样的:

var data = [ 
 
{ 
 
    typeId: 'random1', 
 
    catId: 'random2', 
 
    val: '2' 
 
}, 
 
{ 
 
    typeId: 'random1', 
 
    catId: 'random2', 
 
    val: '3' 
 
}, 
 
{ 
 
    typeId: 'random1', 
 
    catId: 'random4', 
 
    val: '1' 
 
} 
 
]; 
 

 
var groups = data.reduce(function(acc, obj) { 
 
    acc[obj.typeId+'_'+obj.catId] = acc[obj.typeId+'_'+obj.catId] || 0; 
 
    acc[obj.typeId+'_'+obj.catId] += +obj.val; 
 
    return acc; 
 
}, {}); 
 

 

 
var result = Object.keys(groups).map(function(key) { 
 
    return { 
 
    typeId: key.split('_')[0], 
 
    catId: key.split('_')[1], 
 
    val : groups[key] 
 
    } 
 
}); 
 

 
console.log(result);

1

您可以通过typeIdcatId属性使用forEach()环和thisArg参数去组对象。

var arr = [{"typeId":"random1","catId":"random2","val":"2"},{"typeId":"random1","catId":"random2","val":"3"},{"typeId":"random1","catId":"random4","val":"1"}] 
 

 
var result = []; 
 
arr.forEach(function(e) { 
 
    var key = e.typeId + '|' + e.catId 
 
    if(!this[key]) this[key] = e, result.push(this[key]) 
 
    else this[key].val = +this[key].val + +e.val 
 
}, {}); 
 

 
console.log(result)

0

这个怎么样?

for (var i=0; i<array.length; i++) { 
    for (var j=i+1; j<array.length; j++) { 
    if (array[i].typeId == array[j].typeId && array[i].catId == array[j].catId) { 
     array[i].val = parseInt(array[i].val) + parseInt(array[j].val); 
     array.splice(j--, 1); 
    } 
    } 
} 
+0

你不假设数组是排序的(在typeId第一个和catId上),如果不是这样,你最终会得到多个对象,它们使用typeId和catId相同的组合 –

+0

你可以更详细地解释一下,或者给出我举一个例子。 –

+1

尝试与该阵列'变种阵列= [ { TYPEID: 'random1', CATID: 'random2', VAL: '2' }, { TYPEID: 'random2', CATID: 'random2' , VAL: '3' }, { TYPEID: 'random1', CATID: 'random2', VAL: '1' } ];'代替两个对象的这将是3(第一和最后一项具有相同的ID) –

1

您可以使用query-js(*)。尽管如此,该模块还没有被维护。你会做财产以后这样的:

arr.groupBy(function(e){return e.typeId + e.catId;}).each(function(grp){ 
    let first = grp.first(); 
    return { 
      typeId : first.typeId, 
      catId : first.catId, 
      val : grp.sum(function(e){return 0 + e.val;}) 
      }; 
}); 

它将第一组对象,然后做对每个组的计算

(*)请注意,我是完全偏见,你不能把我的字作为建议,但只有建议,因为我是查询的创建者-js