0

I have an object having key-value pairs. Another array has only a partial set of keys. I want a third array that contains only values and that too only for those keys which are present in the second array.

let x= {'Hello':'Monday', 'World':'Tuesday', 'Program':'Wednesday'}
let y = ['Program','Hello']

What I require in output is : y=['Wednesday', 'Monday']

Victor
  • 5,493
  • 1
  • 27
  • 28
Vaishnavi Dongre
  • 241
  • 3
  • 11
  • Is anything stopping you from achieving what you require? Please note that SO is not a **get code for free** site. We solve problems of our fellow developers... – Rajesh Oct 17 '19 at 13:09
  • Possible duplicate of [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Rajesh Oct 17 '19 at 13:13

2 Answers2

2

Try This

let x= {'Hello':'Monday', 'World':'Tuesday', 'Program':'Wednesday'}
let y = ['Program','Hello']

console.log(y.map(val => x[val]));
Mahesh
  • 1,427
  • 2
  • 19
  • 42
  • Please add explanation. Just code is incomplete answer – Rajesh Oct 17 '19 at 13:11
  • code was quite obvious. So didn't feel a need of explanation. Its just a map function of array. – Mahesh Oct 17 '19 at 13:22
  • If it was that obvious, OP would have not asked. Remember, you are answering for readers and they have all levels. So its always better to explain what and why. – Rajesh Oct 17 '19 at 13:40
0

If I understand you correctly, you want to make sure that the result contains only existing values. If so, you need to loop through y values and make sure the x object has a such property.

let x = {'Hello': 'Monday', 'World': 'Tuesday', 'Program': 'Wednesday'},
    y = ['Program', 'Hello', 'Test'],
    z = [];

for (let prop of y) {
  if (prop in x) {
    z.push(x[prop]);
  }
}

console.log(z);
Victor
  • 5,493
  • 1
  • 27
  • 28