Click here to Skip to main content
14,039,097 members
Rate this:
 
Please Sign up or sign in to vote.
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
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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.
   
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

I'd be inclined to use Object.prototype.hasOwnProperty[^] to determine whether the property has been defined:
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.
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:
var value = objects.find(el => !el.hasOwnProperty("age"));
var allValues = objects.filter(el => !el.hasOwnProperty("age"));
   

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web01 | 2.8.190425.1 | Last Updated 21 Mar 2019
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100