0

What I am trying to accomplish is from an array, I want to map all of those values into one object. For example, if I have the following data below

const myKeys = ["prop_1", "prop_2", "prop_3"];

When I map over this array I would like to return an object with 3 properties from the array listed above. Something like this.

const myKeysObj = myKeys.map( key => {
// expected outcome {"prop_1" : "some_value", "prop_2": "some_value", "prop_3": "some_value"}
// actual outcome {key: "some_value"}
return {[key]: "some_value"}
})

What can I do to have all three of my props in my array to be properties for a each object returned?

2
  • The phrasing of your question is confusing. Do you want one object or three? Commented Oct 8, 2018 at 4:07
  • Three. It should be dependent on whatever I am mapping over. Since I am mapping over myKeys, I would expect three objects retuned because of the size of the array. Commented Oct 8, 2018 at 4:09

1 Answer 1

2

It looks like you want to reduce the keys into an object, in which case reduce is more appropriate than .map:

const myKeys = ["prop_1", "prop_2", "prop_3"];
const output = myKeys.reduce((a, key) => {
  a[key] = 'some_value';
  return a;
}, {});
console.log(output);

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

3 Comments

This works!! Thank you sir!! I will select this as the answer when it allows me.
myKeys.reduce((a, key) => Object.assign(a, { [key]: 'some_value' }), {})
@PeterTran Feel free to accept the answer if it solved your problem :)

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.