Array to Object Based on Key

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to convert an array of objects into an object where each object's key is a specified property value of the original objects. We will achieve this by using the Array.prototype.reduce() method and object destructuring in JavaScript. This lab will help you gain a deeper understanding of how to manipulate and transform data in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28160{{"`Array to Object Based on Key`"}} javascript/data_types -.-> lab-28160{{"`Array to Object Based on Key`"}} javascript/arith_ops -.-> lab-28160{{"`Array to Object Based on Key`"}} javascript/comp_ops -.-> lab-28160{{"`Array to Object Based on Key`"}} javascript/array_methods -.-> lab-28160{{"`Array to Object Based on Key`"}} javascript/higher_funcs -.-> lab-28160{{"`Array to Object Based on Key`"}} javascript/spread_rest -.-> lab-28160{{"`Array to Object Based on Key`"}} end

Converting an Array to an Object Based on a Specific Key

To convert an array into an object based on a specific key and exclude that key from each value, follow these steps:

  • Open the Terminal/SSH and type node to start practicing coding.
  • Use Array.prototype.reduce() to create an object from the provided array.
  • Use object destructuring to extract the value of the given key and the associated data, and then add the key-value pair to the object.

Here's an example implementation:

const indexOn = (arr, key) =>
  arr.reduce((obj, v) => {
    const { [key]: id, ...data } = v;
    obj[id] = data;
    return obj;
  }, {});

You can then use the function like this:

indexOn(
  [
    { id: 10, name: "apple" },
    { id: 20, name: "orange" }
  ],
  "id"
);
// { '10': { name: 'apple' }, '20': { name: 'orange' } }

Summary

Congratulations! You have completed the Array to Object Based on Key lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like