获取与特定字符串匹配的json对象数组的长度

时间:2018-03-13 21:57:33

标签: javascript ecmascript-6

假设我有一个名为friends的对象数组

let friends = [
    {"name": "test 1", "type": "pending"}, 
    {"name": "test 2", "type": "friends"}, 
    {"name": "test 3", "type": "friends"},
    {"name": "test 4", "type": "friends"},
    {"name": "test 5", "type": "alien"}
]

我如何获得将被排除在外的朋友的长度?我使用这个,但有更简单的方法吗?

let total = friends.filter(friend=>friend.type==='friends').length + friends.filter(friend=>friend.type==='alien').length;

2 个答案:

答案 0 :(得分:2)

您不需要filter该数组创建新数组然后获取其长度,只需使用函数reduce进行简单计数。



let friends = [    {"name": "test 1", "type": "pending"},     {"name": "test 2", "type": "friends"},     {"name": "test 3", "type": "friends"},    {"name": "test 4", "type": "friends"},    {"name": "test 5", "type": "alien"}],
    count = friends.reduce((a, t) => a + (t.type !== 'pending'), 0);

console.log(count);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:1)

您可以直接使用 let friends = [ {"name": "test 1", "type": "pending"}, {"name": "test 2", "type": "friends"}, {"name": "test 3", "type": "friends"}, {"name": "test 4", "type": "friends"}, {"name": "test 5", "type": "alien"} ]; let count = friends.filter(t=>t.type !== 'pending').length; console.log(count);

进行单一过滤查询

<强>样本

{{1}}