Trusted answers to developer questions

What is the _.keys() method in Underscore.js?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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 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"}
// get keys
console.log(_.keys(obj1))
console.log(_.keys(obj2))
console.log(_.keys(obj3))

Explanation

  • Line 2: We require the underscore.js package.
  • 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.

RELATED TAGS

underscorejs

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
Did you find this helpful?