Object From Pairs

Beginner

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.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

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.