根据数组中的值过滤JSON数据 [英] Filtering JSON Data based on the Values in the Array
本文介绍了根据数组中的值过滤JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Javascript中,有没有一种方法可以根据数组中的值过滤JSON文件?
In Javascript, is there a way to filter the JSON file based on the values in the array?
例如,具有以下数组:
["c", "f"]
和JSON对象文件:
[{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6
},{
"a": 2,
"b": 4,
"c": 6,
"d": 8,
"e": 10,
"f": 12
}]
我想产生以下结果:
[{
"c": 3,
"f": 6
},{
"c": 6,
"f": 12
}]
推荐答案
您可以为新对象映射给定键的值.
You could map the values of the given keys for a new object.
var keys = ["c", "f"],
data = [{ a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }, { a: 2, b: 4, c: 6, d: 8, e: 10, f: 12 }],
filtered = data.map(o => Object.assign(...keys.map(k => ({ [k]: o[k] }))));
console.log(filtered);
这篇关于根据数组中的值过滤JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文