使用lodash合并具有不同键的2个对象数组

时间:2016-11-15 14:59:15

标签: javascript underscore.js lodash

我使用Backbone / lodash作为项目,我希望根据特定值合并2个对象数组。通过下面的示例,合并基于具有2个不同键(id和数字)的相同值。

实施例

var people = [
    {
        id: "1",
        name: "John"
    },
    {
        id: "2",
        name: "Jane"
    }
];

var data = [
    {
        number: "2",
        role: "Designer"
    },
    {
        number: "1",
        role: "Developer"
    }
];

// Outpout

var merge = [
    {
        id: "1",
        number: "1",
        name: "John",
        role: "Developer"
    },
    {
        id: "2",
        number: "2",
        name: "Jane",
        role: "Designer"
    }
];

4 个答案:

答案 0 :(得分:3)

_.map(people, function(p){
    return _.merge(
        p, 
        _.find(data, {number: p.id})
    )
})

答案 1 :(得分:2)

我不知道lodash函数完全符合这个用例。但是,您的目标可以通过纯JavaScript和lodash助手 A_.assign()很好地实现:



_.values()

var people = [{id: "1", name: "John"}, {id: "2", name: "Jane"}];
var data = [{number: "2", role: "Designer"}, {number: "1", role: "Developer"}];

var resultObj = {};

people.forEach(function(item) {
  resultObj[item.id] = item;
});
data.forEach(function(item) {
  resultObj[item.number] = _.assign({}, resultObj[item.number], item);
});

var result = _.values(resultObj);
console.log(result);




答案 2 :(得分:1)

  • 通过连接值对数组进行排序。

  • zipWith将数组压缩在一起。

  • defaults合并每个迭代的对象。



var people = [
    {id: "1", name: "John"},
    {id: "2", name: "Jane"}
];

var data = [
    {number: "2", role: "Designer"},
    {number: "1", role: "Developer"}
];

var result = _.zipWith(
  _.sortBy(people, person => person.id), 
  _.sortBy(data, dataItem => dataItem.number), 
  (person, dataItem) => _.defaults(person, dataItem)
);

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.1/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以使用Array#map()来迭代所有data并使用Array#find()设置p所有p.id === d.number个对象属性:

var people = [{id: "1",name: "John"}, {id: "2",name: "Jane"}],
    data = [{number: "2",role: "Designer"}, {number: "1",role: "Developer"}],
    merge = data.map(d => {
      var p = people.find(p => p.id === d.number);
      p.number = d.number;
      p.role = d.role;

      return p;
    });

// Outpout
console.log(merge);
.as-console-wrapper { max-height: 100% !important; top: 0; }