Luiz Carvalho
Luiz Carvalho

Reputation: 1419

Extract sub-object using keys and create array with keys not unused with javascript

I need extract sub-object from state object using fields array, witch contains keys that I want extract.

And after, I need an Array with unused keys.

My input object

state = {id: '123', number: '456', extra_field: 'value'}
fields = ["id", "number", "identifier"]

Wanted results

missing_fields = ['identifier']
data = {id: '123', number: '456'}

I'm using lodash, if is util!

Upvotes: 0

Views: 213

Answers (1)

s.d
s.d

Reputation: 29436

To select an object with specific keys, use _.pick:

const data = _.pick(state, fields);

To find missing keys, use _.difference of state keys from fields:

const missing = _.difference(fields, _.keys(state));

Upvotes: 1

Related Questions