Blog Post

JS - Object has property with value of

Monday, September 26, 2016 2:24 AM

Task definition

find in array of objects all objects with property value.

 

I have created a small method that does the search for me

 

The full demo you can find in jsfiddle: https://jsfiddle.net/cpoDesign/t9d9817u/

Method:

function hasValue(obj, key, value) {
   return obj.hasOwnProperty(key) && obj[key] === value;
}

Definition of dummy objects array

 

var test = [
  {name : "joey", age: 15},
  {name: "hell", age: 12}
]

 

Now I can run tests:

First negative test:

// returns false due to not matching on item value
console.log(test.some(function(item) { return hasValue(item, "age", 13); }));

Now positive test

// returns true due to not matching on item value
console.log(test.some(function(item) { return hasValue(item, "age", 12); }));

 

Alternative usage like foreach in c#

returns output for all matches in array

// returns output for all matches in array
test.some(function(item) {
if(hasValue(item, "age", 12))
{
console.log(true)
}else{
console.log(false)
}
});
Blog
Products
Error pages
Links and tools