Vaishnavi Dongre
Vaishnavi Dongre

Reputation: 259

Replacing keys by values according to some predefined object in javascript

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']

Upvotes: 0

Views: 35

Answers (2)

Victor
Victor

Reputation: 5769

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);

Upvotes: 0

Mahesh
Mahesh

Reputation: 1635

Try This

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

console.log(y.map(val => x[val]));

Upvotes: 2

Related Questions