Open In App

How to Convert Object to Array in Lodash ?

Last Updated : 29 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Converting an Object to an Array consists of changing the data structure from key-value pairs to an array format.

Below are the different approaches to converting objects to arrays in Lodash:

Run the below command before running the below code on your system:

npm i lodash

Using toArray function

In this approach, we are using Lodash’s toArray function, which converts the values of an object into an array, resulting in an array representation of the object’s properties, useful for array operations and transformations.

Syntax:

_.toArray(value)

Example: The below example uses the toArray function to convert the object to an array in lodash.

JavaScript
const _ = require('lodash');
let obj = { a: 1, b: 2, c: 3 };
let arr = _.toArray(obj);
console.log(arr);

Output:

[ 1, 2, 3 ]

Using values function

In this approach, we are using Lodash’s values function to extract the values of an object and convert them into an array, providing an array representation of the object’s properties for easier array-based operations.

Syntax:

_.values(object)

Example: The below example uses the values function to convert the object to an array in lodash.

JavaScript
const _ = require('lodash');
let obj = { a: 1, b: 2, c: 3 };
let arr = _.values(obj);
console.log(arr);

Output:

[ 1, 2, 3 ]

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads