在javascript

时间:2015-04-22 10:46:26

标签: javascript node.js object

我有2个对象数组如下:

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

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

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

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

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

3 个答案:

答案 0 :(得分:1)

您可以使用underscore js union and uniq来执行此操作。

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

答案 1 :(得分:1)

您可以执行以下操作:

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箭头功能,则result变为

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

答案 2 :(得分:0)

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 i.e 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);