What is the _.keys() method in Underscore.js?
Overview
Underscore.js is a Node.js package that manipulates arrays and objects. We use the keys() method in underscore.js to get all the keys or property names of an object.
Syntax
_.keys(object)
The syntax to use the _.keys() method
Parameters
object: This is the object whose keys or property names we want to get.
Return value
This method returns a list of all keys or properties of an object. This list is an array containing the keys.
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"}// get keysconsole.log(_.keys(obj1))console.log(_.keys(obj2))console.log(_.keys(obj3))
Explanation
- Line 2: We require the
underscore.jspackage. - Lines 5–7: We create three objects with a different number of elements.
- Lines 10–12: We call the
_.keys()method to get the keys of the objects. Then, we print the results to the console.