Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore, check if key exists in array of objects

I am trying to check new data I am receiving against an object I am holding onto, and what I am trying to find out is if they key of the object I am being send matches any keys in the object I currently have.

So I am holding onto an object like

myObj = [{"one": 1}, {"two": 2 },{"three" : 3}];

And I get sent a single object like

{"three" : 5 }

And I want to just check this object against the array of objects (myObj) and see if there is anything with the key "three" inside of it ( I don't care about the values, just the key matching) so I can pop it into an if statement to separate like -

if( array of objects (myObj) has key from single object ( "three" ) ) {}

I am using underscore. Thanks!

Edit : Sorry this was not clear, I am editing it to clarify -

I am holding onto myObj (the array of objects), and being sent a single object - the "three" for example, and I just want to pull that single object key out (Object.keys(updatedObject)[0]) and check if any of the objects in the object array have that key.

So _has seems like it is just for checking a single object, not an array of objects.

like image 744
ajmajmajma Avatar asked Mar 03 '15 15:03

ajmajmajma


People also ask

How to check key exists in array object JavaScript?

Using the indexOf() Method JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.

How do you know if a key is present in an object?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.

How do I check if an object has a key in Lodash?

To check if a key exists in an object with Lodash and JavaScript, we can use the has method. We call has with the obj we want to check if the key exists in and the key we're searching for. Therefore, the first console log logs true and the 2nd one logs false .


2 Answers

You're looking for the _.some iterator combined with a callback that uses _.has:

if (_.some(myObj, function(o) { return _.has(o, "three"); })) {
    …
}
like image 139
Bergi Avatar answered Nov 24 '22 02:11

Bergi


You can use underscore method 'has'

Here the example:

_.has({"three" : 5 }, "three");
=> true

From the underscore doc:

Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe reference to the hasOwnProperty function, in case it's been overridden accidentally.

like image 34
Sergiy Kozachenko Avatar answered Nov 24 '22 03:11

Sergiy Kozachenko