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.
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
Asked: 2021-11-19 11:00:00 +0000
Seen: 11 times
Last updated: Mar 25 '23
Is it feasible to utilize a Toggle Button to switch among multiple classes exceeding 2?
What is the process for generating a dynamic subdomain/URL using vue.js?
How can I create a transition on click using CSS without the need for JavaScript?
How can the style of the loader be modified while the form submission is being processed?
I'm attempting to develop a Javascript-based comments section for my website.
What are some feasible methods to enable MIDI file playback on a web browser?