我有下面的JSON,我想让数组保持相同的格式,但只包括类型为"ar"的对象.我如何用JavaScript过滤这个JSON,使其只包含我需要的类型?

[{"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"},
]

推荐答案

You should use filter method.

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

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";         
}));

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

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

Json相关问答推荐

Vega通孔信号中的动态梯度

如何使用表键名称GROUP_BY

kotlinx-serialization:如何将具有不同类型对象的JsonArray转换为同一个Class

如何在Gatsby/Reaction中获取JSON-File子 node

在ConvertFrom-Json之后需要从PowerShell对象中获取数据

在AWS步骤函数中将字符串解析为JSON&S映射状态

从Postgres表中的JSON中提取值

bash用jq获取第二条JSON记录

Powershell ConvertFrom-Json 意外地从包含字符串的单个项目数组生成字符串而不是对象数组

XSLT 3.0 Json-to-xml,json 包含 html struct

Rust实现:高效解析任意大小的JSON数组

将=分隔值文件转换为:json文件

如何在 Apps 脚本中循环遍历 JSON 响应

为什么根据其他工具,来自 aws rds 的 JSON 在 Docker 中格式错误运行?

流导入错误:重新上传时不存在布局释放 UUID

从ruby中的json获取特定的键值

在 Bash 中访问 JSON 对象 - 关联数组/列表/另一个模型

IE8 原生 JSON.parse 错误导致堆栈溢出

消息通知产生此内容无法显示

使用 JSON.NET 序列化/反序列化对象字典