Object From Pairs

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to create an object from key-value pairs in JavaScript. We will use the Array.prototype.reduce() method to combine the pairs into a single object. Additionally, we will learn about the Object.fromEntries() method, which provides similar functionality. By the end of the lab, you will have a better understanding of how to work with key-value pairs 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/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28519{{"`Object From Pairs`"}} javascript/data_types -.-> lab-28519{{"`Object From Pairs`"}} javascript/arith_ops -.-> lab-28519{{"`Object From Pairs`"}} javascript/comp_ops -.-> lab-28519{{"`Object From Pairs`"}} javascript/array_methods -.-> lab-28519{{"`Object From Pairs`"}} javascript/higher_funcs -.-> lab-28519{{"`Object From Pairs`"}} javascript/destr_assign -.-> lab-28519{{"`Object From Pairs`"}} end

Creating an Object from Key-Value Pairs

To create an object from key-value pairs, use the objectFromPairs function.

  • Open the Terminal/SSH and type node to start practicing coding.
  • The function uses Array.prototype.reduce() to create and combine key-value pairs.
  • For a simpler implementation, you can also use Object.fromEntries().
const objectFromPairs = (arr) =>
  arr.reduce((a, [key, val]) => ((a[key] = val), a), {});

Example usage:

objectFromPairs([
  ["a", 1],
  ["b", 2]
]); // {a: 1, b: 2}

Summary

Congratulations! You have completed the Object From Pairs lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like