I have a big array of objects and i need to get the objects that have the propertie def
set. No mather the value...
Thanks in advance.
Asked
Active
Viewed 44 times
0

Leonel Matias Domingos
- 1,922
- 5
- 29
- 53
-
Possible duplicate of [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – Serge K. Jan 04 '18 at 11:00
-
Possible duplicate of [Filter an array of objects in javascript](https://stackoverflow.com/questions/25388371/filter-an-array-of-objects-in-javascript) – Reinstate Monica Cellio Jan 04 '18 at 11:06
-
1@SergeK. That's not the same question. I read this as they want the objects that have a certain property set, not just that property. – Reinstate Monica Cellio Jan 04 '18 at 11:06
-
@Archer you're probably right, do you think I should remove my vote ? – Serge K. Jan 04 '18 at 11:19
-
1@SergeK. Up to you. I've marked it as a dupe as well so I think it still stands. Between us we've probably found a duplicate :D – Reinstate Monica Cellio Jan 04 '18 at 11:20
2 Answers
5
You can use hasOwnProperty to check if a property is present, and Array.prototype.filter
to filter only those items.
objArray = [ { def: 1, bar: 2}, { foo: 3, bar: 4}, { def: 5, bar: 6} ];
var result = objArray.filter(item => item.hasOwnProperty('def'));
console.log(result);
for es5 compatibility
objArray = [{
def: 1,
bar: 2
}, {
foo: 3,
bar: 4
}, {
def: 5,
bar: 6
}];
var result = objArray.filter(function(item) {
return item.hasOwnProperty('def')
});
console.log(result);

sabithpocker
- 15,274
- 1
- 42
- 75
-
@Archer Which function above has a problem with IE? Is it the fat arrow function you are referring to? – sabithpocker Jan 04 '18 at 11:05
0
There is not such function in lodash although you can try following code
`let aFilteredArray = [];
_.forEach(YourArray,function(oElement){
if(!_.isEmpty(oElement.def)){
aFilteredArray.push(oElement);
}
};

RohanS404
- 41
- 1
- 8