如何使用Underscore.JS通过另一个数组扩展数组对象

时间:2017-09-26 11:02:07

标签: javascript underscore.js

我有以下列表对象:

对象1:

[{
    empId: 1, 
    name: AAA, 
    schoolId: 1
}, {
    empId: 2, 
    name: BBB, 
    schoolId: 2
}]

和对象2:

[{
    schoolId: 1, 
    schoolName: SchoolA
}, {
    schoolId: 2, 
    schoolName: SchoolB
}]

在Object1和Object2这两个对象中,SchoolId是公共字段。可以作为映射字段访问。

现在我使用的_.extend UnderscoreJS方法想要实现以下对象:

输出:

[{
    empId: 1, 
    name: AAA, 
    schoolId: 1, 
    school: SchoolA
}, {
    empId: 2, 
    name: BBB, 
    schoolId: 2, 
    school: SchoolB
}]

您能否建议我如何实现这一目标?感谢

4 个答案:

答案 0 :(得分:0)

使用_.indexBy()创建第一个数组arr1Index的索引(schoolId),然后使用_.map()第二个数组,创建一个扩展当前对象的新对象,使用来自schoolId的<{1}}的对象:

arr1Index
var arr1 = [{"empId":1,"name":"AAA","schoolId":1},{"empId":2,"name":"BBB","schoolId":2}];

var arr2 = [{"schoolId":1,"schoolName":"SchoolA"},{"schoolId":2,"schoolName":"SchoolB"}];

var arr1Index = _.indexBy(arr1, 'schoolId');

var result = _.map(arr2, function(o) {
  return _.extend({}, o, arr1Index[o.schoolId]);
});

console.log(result);

答案 1 :(得分:0)

您可以将eachfindWhere结合使用,如下所示。

var d1 = [{
  empId: 1,
  name: "AAA",
  schoolId: 1
}, {
  empId: 2,
  name: "BBB",
  schoolId: 2
}];

var d2 = [{
  schoolId: 1,
  schoolName: "SchoolA"
}, {
  schoolId: 2,
  schoolName: "SchoolB"
}];

var output = _.each(d1, function(obj) {
  obj.school = _.findWhere(d2, {
    schoolId: obj.schoolId
  }).schoolName;
});

console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

答案 2 :(得分:0)

你可以这样做(注意:这个解决方案要求我们有两个长度相同的数组,第一个数组的第N个元素应该用第二个数组的第N个元素扩展等) :

&#13;
&#13;
var arrayOne = [{
    empId: 1, 
    name: 'AAA', 
    schoolId: 1
}, {
    empId: 2, 
    name: 'BBB', 
    schoolId: 2
}];

var arrayTwo = [{
    schoolId: 1, 
    schoolName: 'SchoolA'
}, {
    schoolId: 2, 
    schoolName: 'SchoolB'
}];

var result = _.map(arrayOne, function(value, index) {
	return _.extend({}, value, arrayTwo[index])
})

console.log(result);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
&#13;
&#13;
&#13;

还有一个补充说法 - 与Lodash一起,这个问题解决得更简洁:

_.zipWith(arrayOne, arrayTwo, _.assign) // ==> returns what you need

Example with Lodash

答案 3 :(得分:0)

您可以使用_extend_find

&#13;
&#13;
var arr1 = [{"empId":1,"name":"AAA","schoolId":1},{"empId":2,"name":"BBB","schoolId":2}];

var arr2 = [{"schoolId":1,"schoolName":"SchoolA"},{"schoolId":2,"schoolName":"SchoolB"}];


var output = _.each(arr1, function(a1) {
    _.extend(a1, _.find(arr2, function(a2) {
        return a2.schoolId == a1.schoolId; 
    }))
});

console.log(output)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
&#13;
&#13;
&#13;