Ask Your Question
0

How can an array be transformed into an object using a specific key as the basis?

asked 2021-11-19 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-03-25 19:00:00 +0000

david gravatar image

To transform an array into an object using a specific key as the basis, you can use the JavaScript reduce method.

Here's an example code snippet:

const array = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Mary'},
  {id: 3, name: 'Bob'}
];

const key = 'id'; // The key to use as the basis of the transformation

const transformedObject = array.reduce((obj, item) => {
  obj[item[key]] = item;
  return obj;
}, {});

console.log(transformedObject);
/*
Output:
{
  '1': {id: 1, name: 'John'},
  '2': {id: 2, name: 'Mary'},
  '3': {id: 3, name: 'Bob'}
}
*/

In this example, we have an array of objects with an id key. We want to transform this array into an object where each object is keyed by its id.

To achieve this, we use the reduce method to iterate over the array and build the object. We initialize the result object as an empty object {}.

For each item in the array, we access its id property using the key variable, and add the entire item as a property to the result object using that id as the key.

At the end of the iteration, the result object contains all the original items keyed by their id property.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-19 11:00:00 +0000

Seen: 11 times

Last updated: Mar 25 '23