Reputation: 393
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
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
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
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
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