This is my Object
var MyObject =[{
first: "Romeo",
last: "Montague"
}, {
first: "Mercutio",
last: null
}];
And this is target property:
var Target = {
last: "Capulet"
};
I want to find out all Object have the target property or not. And from my object and target property above expected result is True because both of them have ‘last’ property
Function to find object:
function Find(obj,source){
const key = Object.keys(source);
console.log(obj.every(keys => obj.hasOwnProperty(key))); /* false*/
console.log(obj[0].hasOwnProperty(key));/*true*/
console.log(obj[1].hasOwnProperty(key));/*true*/
}
I don’t understand why console.log(obj.every(keys => obj.hasOwnProperty(key)));
returns false
but console.log(obj[0].hasOwnProperty(key))
and console.log(obj[1].hasOwnProperty(key))
return true
.
3
Answers
Split your problem into smaller, composable, parts:
The first is easy enough:
The second is then just a matter of wrapping that in an
every
for our data list:And the third is then just a matter of wrapping that in another
every
for our required properties:Now that we know the composition, we can put it all together into a single function and run it on our data:
You have a typo here:
Your
every
callback is declaring a parameter namedkeys
, which you are not using, instead you callhasOwnProperty
on theobj
array again (which indeed does not have thekey
property).Name your variables properly, using plural for things that are arrays, and use only the first of the
Object.keys(…)
as thekey
(you were using a single-element array, which was weird but worked because it was coerced to a string). Corrected:Your code has some flaws:
key
is an array of property names not a property name, useconst [key] = Object.keys(source);
obj.hasOwnProperty
refers toMyObject
array, it should bekeys
. Butkeys
argument name is misleading, use something likeitem
:The solutions:
Here is a generic solution for any number of properties in
Target
. We use the secondArray::every()
here to ensure that every property inTarget
isMyObject
‘s item:For only the first property I would use
in
operator since it seems the fastest:And a benchmark: