user8116198
user8116198

Reputation:

Lodash | Search object for key

I am trying to search an object that I have for a key that matches an input name. This is so I can assign values.

<input type="text" name="first_name"/>

const inputs = document.querySelectorAll('inputs');
const obj = {
    first_name: "Bob",
    last_name: "Marley"
};

I want to match the key first_name onto a input which has the name first_name.

I have got as far as:

_.forEach(inputs, (input) => {
    const value = _.filter(obj, input.name);
    input.value = value;
});

However, I keep getting undefined so I don't believe the filter is the right function to use. However, I have had a look at the documentation and not really seen anything that comes close. I have tried to convert to an array but had no hope there either as all of the keys went to the index number.

Upvotes: 2

Views: 3235

Answers (1)

I think _.get(obj, input.name) is what you are looking for.

Here the docs:

_.get(object, path, [defaultValue])

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

Example:

const obj = {'a':1, 'b':{'c': 2}}
_.get(obj, 'a')   // returns 1
_.get(obj, 'b.c') // returns 2

Upvotes: 4

Related Questions