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.
Here's the syntax for underscore.js:
_.pairs(object)
object
: This is the object we want to convert.
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.
// require underscoreconst _ = require("underscore")// create some objectslet 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() methodlet arr1 = _.pairs(obj1)let arr2 = _.pairs(obj2)let arr3 = _.pairs(obj3)let arr4 = _.pairs(obj4)// print the resultsconsole.log(arr1)console.log(arr2)console.log(arr3)console.log(arr4)
underscore
module.pairs()
method and save the results.