我很确定以前回答过这种问题,但是我无法很好地进行搜索。
我有一个类似的对象数组;
[
{ prop1:"foo1", prop2:"baz1", prop3:"bar1", prop4:"qux1"}
{ prop1:"foo2", prop2:"baz2", prop3:"bar2", prop4:"qux2"}
{ prop1:"foo3", prop2:"baz3", prop3:"bar3", prop4:"qux3"}
]
我有一个数组,用于存储所需的属性名称,例如;
[ "prop1", "prop2" ]
所以我需要使用另一个数组给定的属性名称来过滤数组中的所有对象。输出将是;
[
{ prop1:"foo1", prop2:"baz1" }
{ prop1:"foo2", prop2:"baz2" }
{ prop1:"foo3", prop2:"baz3" }
]
我该如何以正确的方式执行此操作?
答案 0 :(得分:4)
您可以使用pick
方法创建reduce
函数,然后将其与map
方法一起使用。
const data = [{ prop1:"foo1", prop2:"baz1", prop3:"bar1", prop4:"qux1"},{ prop1:"foo2", prop2:"baz2", prop3:"bar2", prop4:"qux2"},{ prop1:"foo3", prop2:"baz3", prop3:"bar3", prop4:"qux3"}]
const props = [ "prop1", "prop2" ]
const pick = (o, p) => p.reduce((r, e) => Object.assign(r, {[e]: o[e]}), {})
const res = data.map(o => pick(o, props));
console.log(res)
答案 1 :(得分:4)
您可以使用map()
和reduce()
const data = [
{ prop1:"foo1", prop2:"baz1", prop3:"bar1", prop4:"qux1"},
{ prop1:"foo2", prop2:"baz2", prop3:"bar2", prop4:"qux2"},
{ prop1:"foo3", prop2:"baz3", prop3:"bar3", prop4:"qux3"}
];
const props = [ "prop1", "prop2" ];
const res = data.map(e => props.reduce((a,c) => (a[c] = e[c] , a), {}));
console.log(res)
答案 2 :(得分:3)
您可以执行以下操作来获得结果:
const data = [
{ prop1:"foo1", prop2:"baz1", prop3:"bar1", prop4:"qux1"},
{ prop1:"foo2", prop2:"baz2", prop3:"bar2", prop4:"qux2"},
{ prop1:"foo3", prop2:"baz3", prop3:"bar3", prop4:"qux3"},
]
const keys = [ "prop1", "prop2" ]
let result = data.map((record) => {
let obj = {}
keys.forEach((key) => {
obj[key] = record[key]
})
return obj
})
console.log(result)
答案 3 :(得分:1)
let arr = [
{ prop1:"foo1", prop2:"baz1", prop3:"bar1", prop4:"qux1"},
{ prop1:"foo2", prop2:"baz2", prop3:"bar2", prop4:"qux2"},
{ prop1:"foo3", prop2:"baz3", prop3:"bar3", prop4:"qux3"}
]
let filter = [ "prop1", "prop2" ];
let out = [...arr].map(e => Object.keys(e).map(k => !filter.includes(k) ? delete e[k] :true) && e);
console.log(out)