简体   繁体   English

使用ES6过滤带有数组的对象

[英]filter the objects with array using ES6

How to find the length of the ARRAY using ES6: 如何使用ES6找到ARRAY的长度:

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. 注意:如果这是单独的数组列表,则aValue.length会起作用。 However, since these are values assigned to properties. 但是,因为这些是分配给属性的值。 Ex; 防爆; a: apple , diff approach required. a:苹果 ,需要差异方法。

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 ? 我需要更换“aValue.length”以找到大于3的值的长度,所以答案是苹果,气球和大象?

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. Object.keys()方法返回对象中包含的所有键的数组。

Objects do not have a length property. 对象没有length属性。 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 Object.getOwnPropertyNames(val).lengthObject.keys(val).length

However, there is a little difference between the two. 但是,两者之间存在一点差异。 Object.getOwnPropertyNames(a) returns all own properties of the object a. Object.getOwnPropertyNames(a)返回对象a的所有属性。 Object.keys(a) returns all enumerable own properties. Object.keys(a)返回所有可枚举的自有属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM