0

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.

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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]));

Comments

1

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.

1 Comment

In my case, I should have an array without id and use array keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.