0

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.

2
  • 3
    First array is not valid. Commented Oct 31, 2017 at 12:43
  • 1
    Expected result is not valid structure either Commented Oct 31, 2017 at 12:48

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the help
Hello here my second array create like this var array_Two = [{colorZero:"black", colorOne:"red", colorTwo:"green", colorThree:"blue", colorFour:"purple", colorFive:"golden"}]; then i am geeting "colorOne":undefind, "colorTwo": undefind, "colorThree": undefind then how can fix it
@Edit, let final = array_one.reduce(function(acc,elem){ acc[elem] = array_Two[0][elem]; return acc; },{});
Thanks for give help and response
2

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

Comments

0

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

Comments

-1

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

1 Comment

want also key with value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.