3

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 ?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this is not an object. this an array. Have u had a chance to run the code using your solution ?
It's an array of objects. Yes, the solution works, it grabs the Object.keys() of each object inside of your array. What trouble are you running into?
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.