Edit
Edit

Reputation: 393

How to compare values in one array with key in another?

I have the following two arrays:

array_Two = [colorZero:"black", colorOne:"red", colorTwo:"green", colorThree:"blue", colorFour:"purple", colorFive:"golden");

array_one = ["colorOne", "colorTwo", "colorThree"];

want like this o/p with final array =>

FinalArray = [colorOne:"red",colorTwo:"green",colorThree:"blue"]

How can I do that? i have no idea any one please know then please let me know.

Upvotes: 0

Views: 75

Answers (4)

Max Larionov
Max Larionov

Reputation: 474

Looks like this is what you are looking for:

array_Two = {colorZero:"black", colorOne:"red", colorTwo:"green", colorThree:"blue", colorFour:"purple", colorFive:"golden"};

array_one = ["colorOne", "colorTwo", "colorThree"];

array_one.forEach(element => {
    console.log(array_Two[element])
})

In this case I have used arrow function syntax which is an ES6 feature. Also, you should have used curly braces for array_Two

Upvotes: -1

Nina Scholz
Nina Scholz

Reputation: 386624

With an object, you could Object.assign and map single objects with spread syntax ....

var object = { colorZero: "black", colorOne: "red", colorTwo: "green", colorThree: "blue", colorFour: "purple", colorFive: "golden" },
    array = ["colorOne", "colorTwo", "colorThree"],
    result = Object.assign(...array.map(k => ({ [k]: object[k] })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Thorgeir
Thorgeir

Reputation: 4433

Something like this?

var array_Two = {colorZero:"black", colorOne:"red", colorTwo:"green", colorThree:"blue", colorFour:"purple", colorFive:"golden"};

var array_one = ["colorOne", "colorTwo", "colorThree"];

var output = {}

array_one.forEach((item) => output[item] = array_Two[item]);

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

Assuming the first object you provided is an object with some keys, you can use reduce method.

array_Two = {colorZero:"black", colorOne:"red", colorTwo:"green", colorThree:"blue", colorFour:"purple", colorFive:"golden"};

array_one = ["colorOne", "colorTwo", "colorThree"];

let final = array_one.reduce(function(acc,elem){
  acc[elem] = array_Two[elem];
  return acc;
},{});
console.log(final);

Upvotes: 2

Related Questions