如何基于属性值合并两个javascript数组?

时间:2015-03-23 17:41:23

标签: javascript arrays array-merge

我有两个数组

array1 = [{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}] 

array2 = [{"Deptid":1,"Deptname":"IT"},{"Deptid":12,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"}] 

输出:

{ "0": { "id": 1, "name": "Michale Sharma", "gender": "Male", "age": 25, "salary": 10000, "Deptid": 1, "Deptname": "IT" }, "1": { "id": 2, "name": "Sunil Das", "gender": "Male", "age": 24, "salary": 5000}, "2": { "id": 3, "name": "Robin Pandey", "gender": "Male", "age": 35, "salary": 45000, "Deptid": 3, "Deptname": "HW" }, "3": { "id": 4, "name": "Mona Singh", "gender": "Female", "age": 27, "salary": 12000 }, "4" :{ "Deptid": 12, "Deptname": "HR" } } 

Image of requested output in table form

我想根据属性值合并它们,例如 id of array1 deptid of array2

这意味着如果id值= 1且Deptid值= 1,则合并记录,如果不是,则保留一个数组中的值,另一个将为null。换句话说, FULL OUTER JOIN的功能。因为数组数据不能是顺序数据,并且长度可能不同。

我在

下尝试了 Jquery.extend
$.extend(true, array1,array2) 

它不接受任何属性,但会合并数组。

我也看过this,但没有帮助。

2 个答案:

答案 0 :(得分:0)

看起来你需要一个自定义逻辑。以下是使用lodash库的示例:

var array1 = [{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}] 
var array2 = [{"Deptid":1,"Deptname":"IT"},{"Deptid":12,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"}] 

var defaults = {
    Deptid: null,
    DeptName: null
};

_.each(array1, function (obj) {
    var dept = _.find(array2, { Deptid: obj.id });
    _.defaults(obj, dept, defaults);
});

答案 1 :(得分:0)

使用LoDash,大概是这样的:

_.reduce(array1, function(res, item1) {
  var found = _.find(array2, function(item2) {
    return item1.id === item2.Deptid;
  });
  if (found) res.push(_.merge({}, item1, found));
  return res;
}, []);
编辑:抱歉,我忘了合并空道具。

这将是这样的(未经优化):

function join(array1, array2) {
  var keys = _.keys(array2[0]);
  var vals = _.map(keys, function() { return '' });

  return _.map(array1, function(item1) {
    var found = _.find(array2, function(item2) {
      return item1.id === item2.Deptid;
    });

    if (found)
      return _.merge({}, item1, found);

    return _.merge({}, item1, _.zipObject(keys, vals));
  }, []);  
}