如何从一个对象数组中提取一些属性,比如没有for循环,使用map或filter?
示例:
obj = [
{ 'cars' : 15, 'boats' : 1, 'smt' : 0 },
{ 'cars' : 25, 'boats' : 11, 'smt' : 0 }
]
extractFunction(obj, ['cars' , 'boats']) -> { 'cars' : [15,25], 'boats' : [1,11]}
答案 0 :(得分:1)
您可以使用键来映射值,从而采用动态方法。
function extractFunction(array, keys) {
return array.reduce(
(r, o) => (keys.forEach(k => r[k].push(o[k])), r),
Object.assign(...keys.map(k => ({ [k]: [] })))
);
}
console.log(extractFunction([{ cars: 15, boats: 1, smt: 0 }, { cars: 25, boats: 11, smt: 0 }], ['cars', 'boats']));
答案 1 :(得分:0)
您可以使用reduce:
执行此操作 * 正如您所看到的,这种方法的好处(根据其他答案)是您只需循环keys
一次。
const extractFunction = (items, keys) => {
return items.reduce((a, value) => {
keys.forEach(key => {
// Before pushing items to the key, make sure the key exist
if (! a[key]) a[key] = []
a[key].push(value[key])
})
return a
}, {} )
}
obj = [
{ 'cars' : 15, 'boats' : 1, 'smt' : 0 },
{ 'cars' : 25, 'boats' : 11, 'smt' : 0 }
]
console.log(extractFunction(obj, ['cars', 'boats']))