在javascript中合并对象

我有2个对象数组如下:

arr1 = [ { 'v1': 'abcde', 'pv_45': 13018, 'geolocation': '17.340291,76.842807' }] arr2 =[{ 'v1':'abcde', 'pv_50': 13010, geolocation: '17.340291,76.842807' }] 

我想based on condition that 'v1' and 'geolocation' should be same如下based on condition that 'v1' and 'geolocation' should be same合并上面的2个数组int0 single:

 [{'v1':'abcde', 'pv_45': 13018, 'pv_50': 13010, 'geolocation': '17.340291,76.842807'}] 

我使用_.extend,但它不盲目检查任何条件,它会合并。 请分享你的想法。 提前致谢。

你可以使用下划线js union and uniq来做到这一点。

 var mergedArray = _.uniq(_.union(c1, c2), false, function(item, key, a){ return item; }); 

使用纯JavaScript可以这样做:

 var arr1 = [ { 'v1': 'abcde', 'pv_45': 13018, 'geolocation': '17.340291,76.842807' }], arr2 =[{ 'v1':'abcde', 'pv_50': 13010, geolocation: '17.340291,76.842807' }], mergeOnV1Geo = function (arr1, arr2) { var mergeObj = {}, merge = function (item) { var key = item.v1 + ',' + item.geolocation; // if this is the first object with this key // create a new object and copy v1, geolocation info if (!mergeObj[key]) { mergeObj[key] = { v1: item.v1, geolocation: item.geolocation }; } // add other props Object.keys(item).forEach(function (prop) { if (!prop.match(/v1|geolocation/)) { mergeObj[key][prop] = item[prop]; } }); }; arr1.forEach(merge); arr2.forEach(merge); // map back into an array return Object.keys(mergeObj).map(function (key) { return mergeObj[key]; }); }; mergeOnV1Geo(arr1, arr2); 

你可以做到以下几点:

 var arr3 = [].concat.apply([], arr1, arr2); var temp =_.groupBy(arr3, 'geolocation'); var result = Object.keys(_.groupBy(arr3, 'geolocation')).map(function(x) { return _.extend.apply(0, p[x]); }) 

如果您更喜欢ES-6箭头function, result就变成了

 Object.keys(_.groupBy(arr3, 'geolocation')).map((x) => _.extend.apply(0, p[x]);) 

ES6:使用spread operatorreduce

 arr1 = [{ v1: 'abcde', pv_45: 13018, geolocation: '17.340291,76.842807' }] arr2 =[{ v1:'abcde', pv_50: 13010, geolocation: '17.340291,76.842807' }] // Keys to be grouped ie whose values should be equal groupableKeys = ['v1', 'geolocation']; // Reducer that creates an Object with Key as the // groupable key values value1::value2 and Value as // the list of objects whose v1 and geolocation are same groupableReducer = (a, b) => { const uniqKey = groupableKeys.map(key => b[key]).join("::"); a[uniqKey] = [...(a[uniqKey] || []), b]; return a; } // Merges two objects using the spread operator mergableReducer = (a, b) => ({...a, ...b}) // Merge two arrays and start processing groupableKeyObject = [...arr1, ...arr2].reduce(groupableReducer, {}) output = Object.keys(groupableKeyObject) .map(key => groupableKeyObject[key].reduce(mergableReducer, {}) ) console.log(output);