我有两个JavaScript对象,如下所示。
obj1 = {
sdfjjweifh: {
user: "bob@bob.com",
id: "10"
},
fjemsnduci: {
user: "fred@fred.com",
id: "20"
},
dhcnwodpcu: {
user: "joe@joe.com",
id: "30"
}
};
obj2 = [{
Name: "Bob",
Id: "10"
}, {
Name: "Fred",
Id: "20"
}, {
Name: "Joe",
Id: "30"
}];
我想将其与“ id”字段匹配的结果结合起来:
obj1 = {
sdfjjweifh: {
user: "bob@bob.com",
id: "10",
Name: "Bob"
},
fjemsnduci: {
user: "fred@fred.com",
id: "20",
Name: "Fred"
},
dhcnwodpcu: {
user: "joe@joe.com",
id: "30",
Name: "Joe"
}
};
使用纯javascript / ES6最简单的方法是什么?
我发现很多与此相关的东西,但不能完全整合在一起。
答案 0 :(得分:0)
您可以在if(isset($_SESSION['login_account_id'])){
header('location: /index.php');
}
的键上使用forEach()
循环,以便对于obj1
的每个属性,可以在数组obj1
中找到对应的匹配对象:>
obj2
答案 1 :(得分:0)
使用for..in
遍历对象并从每个对象获取ID。然后使用数组findIndex
从Id
匹配的数组中获取对象的索引。如果Id匹配,则从数组中获取其名称,然后在对象中添加新键
let obj1 = {
sdfjjweifh: {
user: "bob@bob.com",
id: "10"
},
fjemsnduci: {
user: "fred@fred.com",
id: "20"
},
dhcnwodpcu: {
user: "joe@joe.com",
id: "30"
}
};
let obj2 = [{
Name: "Bob",
Id: "10"
}, {
Name: "Fred",
Id: "20"
}, {
Name: "Joe",
Id: "30"
}];
for (let keys in obj1) {
if (obj1[keys].hasOwnProperty('id')) {
let keyIndex = obj2.findIndex(function(item) {
return item.Id === obj1[keys].id
});
if (keyIndex !== -1) {
obj1[keys].Name = obj2[keyIndex].Name
}
}
}
console.log(obj1)