[英]Nested forEach loops to add object to existing object javascript
Is there a better way to iterate over two array of objects than what I have done below? 有没有比我在下面做的更好的方法来迭代两个对象数组? It seems messy to do it this way. 这样做似乎很麻烦。 I'm using lodash. 我正在使用lodash。
var array1 = [
{id:4356, name: 'James', sex: 'male'},
{id:7899, name: 'Jimmy', sex: 'male'},
{id:2389, name: 'Dawn', sex: 'female'}
];
var array2 = [
{id:4356, salary: 1000, job: 'programmer'},
{id:7899, salary: 2000, job: 'tester'},
{id:2389, salary: 3000, job: 'manager'}
];
Example output: 示例输出:
console.log(array1[0])
{
id:4356,
name: James,
sex: male,
person: {
id:4356,
salary: 1000,
job: programmer
}
}
Function: 功能:
_.forEach(array1, function(item1) {
_.forEach(array2, function(item2) {
if(item1.id === item2.id){
item1.person = item2;
}
});
});
Since you're using lodash, you could use the _.find()
method to find the corresponding object in array2
based on the id
properties. 由于您使用的是lodash,因此可以使用_.find()
方法根据id
属性在array2
查找相应的对象。
_.forEach(array1, function(item1) {
item1.person = _.find(array2, {id: item1.id});
});
It's worth pointing out that this will result in an undefined person
property if an object isn't found. 值得指出的是,如果找不到对象,这将导致未定义的person
属性。 If that's a problem, simply check to see if an object is returned: 如果这是一个问题,只需检查是否返回了一个对象:
_.forEach(array1, function(item1) {
var obj = _.find(array2, {id: item1.id});
if (obj) {
item1.person = obj;
}
});
Without lodash, it would be pretty similar: 没有lodash,它会非常相似:
array1.forEach(function(item1) {
item1.person = array2.find(function (item2) {
return item2.id === item1.id;
});
});
I would build a reference object and add to it, that way you're not loading the second array N times. 我会构建一个引用对象并添加到它,这样你就不会加载第二个数组N次。 Something like this: 像这样的东西:
var array1 = [{id:4356, name: 'James', sex: 'male'},
{id:7899, name: 'Jimmy', sex: 'male'},
{id:2389, name: 'Dawn', sex: 'female'}
];
var array2 = [{id:4356, salary: 1000, job: 'programmer'},
{id:7899, salary: 2000, job: 'tester'},
{id:2389, salary: 3000, job: 'manager'}
];
var array3 = {};
for(var i in array1) {
array3[array1[i]['id']] = array1[i];
}
for(var i in array2) {
for(var key in array2[i]) {
array3[array2[i]['id']][key] = array2[i][key];
}
}
This gives you an object with the properties of both arrays like: 这为您提供了一个具有两个数组属性的对象,如:
Object {2389: Object, 4356: Object, 7899: Object}
With the benefit that you only iterate over each array once. 这样做的好处是只能迭代每个数组一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.