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.
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.iteratoris defined for the given iterable object. - If
Symbol.iteratoris defined, it usesArray.prototype.entries()to get an iterator for the object and then converts the result to an array of key-value pair arrays usingArray.from(). - If
Symbol.iteratoris not defined for the object, it usesObject.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.