我有2个对象:
Obj1 = {
0: "AS1",
1: "AS2",
2: "AS3"
}
Obj2 = {
AS1: "Hani"
AS2: "Joe"
}
我想将Obj1
的值与Obj2
的键进行比较,并打印Obj2
的值。
答案 0 :(得分:2)
您可以使用一个值为obj1
的数组,并迭代obj2
的键。
var obj1 = { 0: "AS1", 1: "AS2", 2: "AS3" },
obj2 = { AS1: "Hani", AS2: "Joe" },
result = Object.assign([], obj1).map(k => k in obj2 ? obj2[k] : null);
console.log(result);
答案 1 :(得分:1)
我不确定您想要实现什么,但是您可以像这样访问所需的值:
let Obj1values = Object.values(Obj1);
console.log(Obj1values)
let Obj2Keys = Object.keys(Obj2);
console.log(Obj2Keys)
答案 2 :(得分:1)
let ob1 = {0: "AS1", 1: "AS2", 2: "AS3" }
let ob2 = {AS1: "Hani", AS2: "Joe" }
let ob1Vals = Object.values(ob1)
let ob2Keys = Object.keys(ob2)
console.log(ob1Vals, ob2Keys)
ob2Keys.forEach(e => {
if(ob1Vals.includes(e)) {
console.log(ob2[e])
}
})
答案 3 :(得分:1)
这基本上等同于Excel的VLOOKUP函数(没有精确匹配选项)。
通过当前User
的值搜索源对象,然后返回Name
的值。由于这是标量值,因此不需要字段/索引。
const lookup = (value, source, field) => {
return ((match) => {
return match && field ? match[field] : match || null;
})(source[value]);
}
let Users = {
0: "AS1",
1: "AS2",
2: "AS3"
}
let Names = {
AS1: "Hani",
AS2: "Joe"
}
console.log(Object.keys(Users).map(id => {
return lookup(Users[id], Names);
}));
.as-console-wrapper { top: 0; max-height: 100% !important; }