Click here to Skip to main content
15,895,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Say I have an array of objects:
[{name:"Chris", age:14, loc:"kw"},{name:"Eric", loc:"kw"}]
How do I find the object without property age i.e.objects[1]

What I have tried:

objects.find(function(el){return element.age===undefined})
Posted
Updated 21-Mar-19 5:41am

Your line of code would almost work, but inside the function you use element.age but element does not exist; you called your parameter el. Try el.age instead.
 
Share this answer
 
I'd be inclined to use Object.prototype.hasOwnProperty[^] to determine whether the property has been defined:
JavaScript
var value = objects.find(function(el){ return !el.hasOwnProperty("age"); });

NB: Array.prototype.find[^] will find the first element which matches. If you want to find all matching elements, use Array.prototype.filter[^] instead.
JavaScript
var allValues = objects.filter(function(el){ return !el.hasOwnProperty("age"); });

Note that both functions have limited support in older browsers. There are polyfills available.

If you're only supporting newer browsers - specifically not Internet Explorer - you might also want to consider using Arrow functions[^] to simplify the code:
JavaScript
var value = objects.find(el => !el.hasOwnProperty("age"));
var allValues = objects.filter(el => !el.hasOwnProperty("age"));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900