-2

I have an Array of Objects something like this

[
  {name: "John", country: "USA", revision: 1},
  {name: "Mark", country: "England", revision: 0},
  {name: "Bruce", country: "France", revision: 1}
]

I want to convert it into an object with key value pair with name key, like this

{
  John : {name: "John", country: "USA", revision: 1},
  Mark : {name: "Mark", country: "England", revision: 0},
  Bruce : {name: "Bruce", country: "France", revision: 1}
}

This is what I have done but it does not seems to work

let component = contents.reduce(((content, current}) => {
    content[name] = current;
    return content;
}), {});
2
  • 3
    What have you tried so far to solve this on your own? A simple for loop should be enough to get the expected output. Commented Nov 2, 2020 at 15:24
  • does this help? stackoverflow.com/questions/49271554/… Commented Nov 2, 2020 at 15:26

1 Answer 1

1

This can be done using Array.prototype.reduce func.

const input = [
  {name: "John", country: "USA", revision: 1},
  {name: "Mark", country: "England", revision: 0},
  {name: "Bruce", country: "France", revision: 1}
];

const output = input.reduce((acc, {name, ...item}) => {
  acc[name] = item;
  return acc;
}, {});
console.log(output);

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

1 Comment

You may use destructuring of .reduce() arguments: input.reduce((acc, {name, ...rest}) => (acc[name] = item, acc), {})

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.