Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  184] [ 6]  / answers: 1 / hits: 96724  / 11 Years ago, thu, october 10, 2013, 12:00:00

I wanted to check if the an object has a property of something and its value is equal to a certain value.



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


There you go, an array of objects, now I wanted to search inside the object and return true if the object contains what I wanted.



I tried to do it like this:



Object.prototype.inObject = function(key, value) {
if (this.hasOwnProperty(key) && this[key] === value) {
return true
};
return false;
};


This works, but not in an array. How do I do that?


More From » jquery

 Answers
23

Use the some Array method to test your function for each value of the array:



function hasValue(obj, key, value) {
return obj.hasOwnProperty(key) && obj[key] === value;
}
var test = [{name : joey, age: 15}, {name: hell, age: 12}]
console.log(test.some(function(boy) { return hasValue(boy, age, 12); }));
// => true - there is a twelve-year-old boy in the array


Btw, don't extend Object.prototype.


[#75086] Wednesday, October 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;