Oleg Ovcharenko
Oleg Ovcharenko

Reputation: 537

Lodash. How to get array values from object if you know array keys?

For example, you have an object.

{ id: 1, firstName: 'John', lastName: 'Doe' }

How to get an array from the object if you know array keys? You have array keys

['firstName', 'lastName']

and you should get array

['John', 'Doe']

I use Lodash.

Upvotes: 0

Views: 58

Answers (3)

Ori Drori
Ori Drori

Reputation: 191976

You can you _.at():

const obj = { id: 1, firstName: 'John', lastName: 'Doe' };
const keys = ['firstName', 'lastName'];

const result = _.at(obj, keys);
console.log('RESULT:', result);
<script src='https://cdn.jsdelivr.net/lodash/4.16.6/lodash.min.js'></script>

Upvotes: 2

Diamond
Diamond

Reputation: 3428

You don't need lodash.

Just use Array.prototype.map to get values from key array.

const obj = { id: 1, firstName: 'John', lastName: 'Doe' };
const filterKey = ['firstName', 'lastName'];

console.log('FILTERED:', filterKey.map(key => obj[key]));

Upvotes: 2

Nicolae Maties
Nicolae Maties

Reputation: 2655

const keys = Object.keys({ id: 1, firstName: 'John', lastName: 'Doe' });
const values = Object.values({ id: 1, firstName: 'John', lastName: 'Doe' });

console.log(keys)
console.log(values)
You don't need to use Lodash, using plain javascript will do it. Use Object.keys() for getting all the keys of an object and Object.values() to get an array with all the values that an object has.

Upvotes: 1

Related Questions