Convert Object to Iterable Pairs

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will be exploring a JavaScript function called "toPairs", which creates an array of key-value pair arrays from an object or other iterable. Through this lab, we will learn how to use this function to convert various data structures into a format that is more easily manipulated and accessed. We will also gain a deeper understanding of the concepts of iterators and iterable objects 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/AdvancedConceptsGroup -.-> javascript/destr_assign("Destructuring Assignment") subgraph Lab Skills javascript/variables -.-> lab-28655{{"Convert Object to Iterable Pairs"}} javascript/data_types -.-> lab-28655{{"Convert Object to Iterable Pairs"}} javascript/arith_ops -.-> lab-28655{{"Convert Object to Iterable Pairs"}} javascript/comp_ops -.-> lab-28655{{"Convert Object to Iterable Pairs"}} javascript/destr_assign -.-> lab-28655{{"Convert Object to Iterable Pairs"}} end

Converting an Object to Pairs

To convert an object to an array of key-value pairs, use the toPairs function. To get started with coding, open the Terminal/SSH and type node.

The toPairs function works in the following way:

  • First, it checks if Symbol.iterator is defined for the given iterable object.
  • If Symbol.iterator is defined, it uses Array.prototype.entries() to get an iterator for the object and then converts the result to an array of key-value pair arrays using Array.from().
  • If Symbol.iterator is not defined for the object, it uses Object.entries() instead.

Here's the code for the toPairs function:

const toPairs = (obj) =>
  obj[Symbol.iterator] instanceof Function && obj.entries instanceof Function
    ? Array.from(obj.entries())
    : Object.entries(obj);

You can use the toPairs function with various types of objects, such as:

toPairs({ a: 1, b: 2 }); // [['a', 1], ['b', 2]]
toPairs([2, 4, 8]); // [[0, 2], [1, 4], [2, 8]]
toPairs("shy"); // [['0', 's'], ['1', 'h'], ['2', 'y']]
toPairs(new Set(["a", "b", "c", "a"])); // [['a', 'a'], ['b', 'b'], ['c', 'c']]

Summary

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