Reputation: 537
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
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
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
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)
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