What is the _.values() method in Underscore.js?
Overview
We use Underscore.js to manipulate objects and arrays. The values() method is used to return all the values of the properties of an object. These values will be returned as an array.
Syntax
_.values(Object)
Syntax for values() method in Underscore.js
Parameters
Object: This is the object whose properties' values we want to get in the array.
Return value
It returns an array of values of each property or key of an object.
Example
// 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"}// get valuesconsole.log(_.values(obj1))console.log(_.values(obj2))console.log(_.values(obj3))console.log(_.values(obj4), _.values(obj4)[2]) // get third item from the list returned as well
Explanation
- Line 2: We import the
underscorepackage. - Lines 5–8: We create some objects.
- Lines 11–14: We use the
values()method to get an array of all the values of all the properties of the objects. Next, we print the values to the console.