Trusted answers to developer questions

What is the _.pairs() method in underscore.js?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Overview

With the underscore.js node module, we can manipulate arrays and objects with simple functions. The pairs() method converts an object to a single array containing key-value pairs. These key-value pairs will be in the form of arrays.

Syntax

Here's the syntax for underscore.js:

_.pairs(object)
The syntax for the pairs() method using underscore.js

Parameters

object: This is the object we want to convert.

Return value

The value returned is an array. This array will contain key-value pairs in the form of an array, which are the properties and values of the object.

Example

// require underscore
const _ = require("underscore")
// create some objects
let obj1 = {one: 1, two: 2, three: 3, four: 4}
let obj2 = {name: "nodejs", package: "underscore", tag: "_"}
let obj3 = {a: "Apple", b: "Banana"}
let obj4 = {M: "Monday", T: "Tuesday", W: "Wednesday"}
// convert the objects using pairs() method
let arr1 = _.pairs(obj1)
let arr2 = _.pairs(obj2)
let arr3 = _.pairs(obj3)
let arr4 = _.pairs(obj4)
// print the results
console.log(arr1)
console.log(arr2)
console.log(arr3)
console.log(arr4)

Explanation

  • Line 2: We require the underscore module.
  • Lines 5–8: We create some objects.
  • Lines 11–14: We convert each object using the pairs() method and save the results.
  • Lines 17–20: We print the results to the console.

RELATED TAGS

underscore.js

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
Did you find this helpful?