[英]How do I assign property values for objects in one array based on key/value pairs in another?
I have an array that looks like this: 我有一个看起来像这样的数组:
var fields = [{Name: 'FirstName', Value: '', Display: 'First Name'}, {...}]
I have another array that looks like this: 我有另一个看起来像这样的数组:
var nameValue = [{'FirstName':'John'}, {'LastName':'Doe'}, ...]
How do I assign the Value property for each field in the first array using the name/value pairs in the second array? 如何使用第二个数组中的名称/值对为第一个数组中的每个字段分配Value属性?
Desired result: 所需结果:
fields = [{Name: 'FirstName', Value: 'John', Display: 'First Name'}, {...}]
You could create an object first with all needed values and iterate fields
, make a check if a property with the name exists and then assign the value. 您可以先创建一个具有所有必需值和迭代fields
的对象,检查是否存在具有名称的属性,然后分配该值。
var fields = [{ Name: 'FirstName', Value: '', Display: 'First Name' }], nameValue = [{ FirstName: 'John' }, { LastName: 'Doe' }], values = Object.assign({}, ...nameValue); fields.forEach(o => (o.Name in values) && (o.Value = values[o.Name])); console.log(fields);
Loop, check, assign: 循环,检查,分配:
fields.forEach(function(field) {
let key = field.Name;
for (let i = 0; i < nameValue.length; i++) {
for (let nameKey in nameValue[i]) {
if (nameKey == key) {
field.Value = nameValue[i][key]
break;
}
}
}
});
First combine all the names and values into a single object: 首先将所有名称和值组合到一个对象中:
var nvObject = {};
nameValue.forEach(function (e) {
for (key in e) {
nvObject[key] = e[key];
}
});
Now nvObject = { FirstName: 'John', LastName: 'Doe', ... }
. 现在nvObject = { FirstName: 'John', LastName: 'Doe', ... }
。 Perhaps you could construct nameValue
like this in the first place, instead of making it an array of objects. 也许您可以首先构造像这样的nameValue
,而不是使其成为对象数组。
Then you can use this to update the other array. 然后,您可以使用它来更新另一个阵列。
$fields.forEach(function (e) {
if (e.Name in nvObject) {
e.Value = nvObject[e.Name];
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.