-2

I have 2 objects:

Obj1 = {
  0: "AS1",
  1: "AS2",
  2: "AS3"
}


Obj2 = {
  AS1: "Hani"
  AS2: "Joe"
}

I want to compare the value of Obj1 with the key of Obj2 and print Obj2 values.

Dan
  • 59,490
  • 13
  • 101
  • 110
Hani Gerges
  • 92
  • 1
  • 11

4 Answers4

2

You could take an array with the values of obj1 and iterate for the keys of 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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

I'm not sure what is it that you want to achieve but You can access the values you need like this:

let Obj1values = Object.values(Obj1);

console.log(Obj1values)

let Obj2Keys = Object.keys(Obj2);

console.log(Obj2Keys)

AdamKniec
  • 1,607
  • 9
  • 25
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])
    }
})
Arpit
  • 467
  • 1
  • 8
  • 18
  • Although this code might solve the problem, a good answer should also explain what it does and how it helps. – BDL Mar 26 '20 at 10:37
1

This is essentially the equivalent to Excel's VLOOKUP function (sans the exact match option).

Search the source object by the value of the current User and return the Name value. Since this is a scalar value, no field/index is needed.

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; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132