在Javascript中,有没有办法根据数组中的值过滤JSON文件?
例如,使用以下数组:
["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
}]
答案 0 :(得分:4)
您可以映射新对象的给定键的值。
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);

答案 1 :(得分:0)
您可以使用map()
和reduce()
。
var keys = ["c", "f"];
var arr = [{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6},{"a":2,"b":4,"c":6,"d":8,"e":10,"f":12}];
var result = arr.map(o => {
return keys.reduce((r, k) => (o[k] && (r[k] = o[k]), r), {})
})
console.log(result)