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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With