DEV Community

Discussion on: Share a code snippet in any programming language and describe what's going on

Collapse
 
booleanhunter profile image
Ashwin Hariharan • Edited

A snippet that I use in my projects:

function convertArrayToObject (array, key) {
    return array.reduce((accumulator, current) => {
        accumulator[current[key]] = current;
        return accumulator;
    }, {});
}
Enter fullscreen mode Exit fullscreen mode

What does this do?

As the name suggests, it converts an array into an object.

When should I use this

Often when you have a big list of objects and you need to look up a value in one of those objects very often, it is useful to transform the list into a object beforehand. It's more efficient that way, than having to do a find element operation by iterating over an array every single time.

Example

// Suppose I have an array of objects, like this:
const tweets = [
    { id: "01", text: "What's your hobby"},
    { id: "02", text: "What are you doing during COVID-19" },
    { id: "03", text: "Share some good fiction books" },
];

const tweetsById = convertArrayToObject(tweets, "id");

// Now I can do this:
console.log(tweetsById["01"].name); // prints "What's your hobby"
Enter fullscreen mode Exit fullscreen mode