按键值过滤JSON [英] Filter JSON by key value

查看:63
本文介绍了按键值过滤JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下JSON,我希望将数组保持相同的格式,但仅包含类型为"ar"的对象.如何使用JavaScript过滤此JSON,使其仅包含我需要的类型?

I have the following JSON and I want to keep the array in the same format but only include objects with type "ar". How can I filter this JSON with JavaScript to only include the types I need?

[{"time":"2016-07-26 09:02:27","type":"aa"},
{"time":"2016-04-21 20:35:07","type":"ae"},
{"time":"2016-08-20 03:31:57","type":"ar"},
{"time":"2017-01-19 22:58:06","type":"ae"},
{"time":"2016-08-28 10:19:27","type":"ae"},
{"time":"2016-12-06 10:36:22","type":"ar"},
{"time":"2016-07-09 12:14:03","type":"ar"},
{"time":"2016-10-25 05:05:37","type":"ae"},
{"time":"2016-06-05 07:57:18","type":"ae"},
{"time":"2016-10-08 22:03:03","type":"aa"},
{"time":"2016-08-13 21:27:37","type":"ae"},
{"time":"2016-04-09 07:36:16","type":"ar"},
{"time":"2016-12-30 17:20:08","type":"aa"},
{"time":"2016-03-11 17:31:46","type":"aa"},
{"time":"2016-05-04 14:08:25","type":"ar"},
{"time":"2016-11-29 05:21:02","type":"ar"},
{"time":"2016-03-08 05:46:01","type":"ar"},
]

推荐答案

您应使用filter方法.

filter()方法创建一个新的array,其中所有通过测试的元素均由提供的功能实现.

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

提供的功能是callback,它应用于数组的每个元素.

Provided function is a callback which is applied to each element of the array.

var arr = [{"time":"2016-07-26 09:02:27","type":"aa"}, {"time":"2016-04-21 20:35:07","type":"ae"}, {"time":"2016-08-20 03:31:57","type":"ar"}, {"time":"2017-01-19 22:58:06","type":"ae"}, {"time":"2016-08-28 10:19:27","type":"ae"}, {"time":"2016-12-06 10:36:22","type":"ar"}, {"time":"2016-07-09 12:14:03","type":"ar"}, {"time":"2016-10-25 05:05:37","type":"ae"}, {"time":"2016-06-05 07:57:18","type":"ae"}, {"time":"2016-10-08 22:03:03","type":"aa"}, {"time":"2016-08-13 21:27:37","type":"ae"}, {"time":"2016-04-09 07:36:16","type":"ar"}, {"time":"2016-12-30 17:20:08","type":"aa"}, {"time":"2016-03-11 17:31:46","type":"aa"}, {"time":"2016-05-04 14:08:25","type":"ar"}, {"time":"2016-11-29 05:21:02","type":"ar"}, {"time":"2016-03-08 05:46:01","type":"ar"}, ];

console.log(arr.filter(function(item){
    return item.type == "ar";         
}));

此外,您可以将shorter方式与arrow 功能一起使用:

Also, you can use a shorter way with arrow functions:

var filtered = arr.filter(a => a.type == "ar");

这篇关于按键值过滤JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆