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.

5
  • possible duplicate of Check if a key exists inside a json object Commented Mar 3, 2015 at 15:38
  • 1
    Google "javascript check if key exists in object" returns three relevant results. Commented Mar 3, 2015 at 15:38
  • 1
    @SergiuParaschiv: not a duplicate at all. Its underscore.js Commented Mar 3, 2015 at 15:40
  • Not a duplicate, this regards using underscore, maybe we should remove the javascript tag to avoid confusion Commented Mar 3, 2015 at 15:44
  • The only reason anyone would use anything other than hasOwnProperty would be browser support, right? Commented Mar 3, 2015 at 17:32

2 Answers 2

13

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

if (_.some(myObj, function(o) { return _.has(o, "three"); })) {
    …
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

This is on the right track - however it is not checking if the array of objects has "three".

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.