5

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.

ajmajmajma
  • 13,712
  • 24
  • 79
  • 133

2 Answers2

13

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

if (_.some(myObj, function(o) { return _.has(o, "three"); })) {
    …
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
10

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.

Sergiy Kozachenko
  • 1,399
  • 11
  • 31