Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter the objects with array using ES6

How to find the length of the ARRAY using ES6:

var x = [{a:"apple", b:"Baloon"},{a:"elephant", b:"dog"}];

var results = x.filter(aValue => aValue.length > 3);

console.log(results);

Note: aValue.length would have worked if this is individual list of array. However, since these are values assigned to properties. Ex; a: apple, diff approach required.

What's the correct code that I need to replace "aValue.length" to find the length of the value greater than 3, so the answer would be apple, baloon and elephant ?

like image 738
thirdEye Avatar asked Jan 26 '26 22:01

thirdEye


2 Answers

This will work for your needs

var results = x.filter(val => Object.keys(val).length > 3)

The Object.keys() method returns an array of all the keys contained in your object.

like image 56
Christopher Messer Avatar answered Jan 28 '26 15:01

Christopher Messer


Objects do not have a length property. But there is a little trick with which you can have the number of keys of an object.

There are 2 methods that can be used. Object.getOwnPropertyNames(val).length and Object.keys(val).length

However, there is a little difference between the two. Object.getOwnPropertyNames(a) returns all own properties of the object a. Object.keys(a) returns all enumerable own properties.

like image 30
rootkill Avatar answered Jan 28 '26 14:01

rootkill