Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.