javascript - 从对象数组中提取一些属性
问题描述
如何从对象数组中提取一些属性,例如没有 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]}
解决方案
您可以使用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']))
推荐阅读
- css - 如何在 Jekyll 中增加图像周围的填充
- tsql - 选择日期和计数,按日期分组 - 如何显示具有 NULL 计数的日期?
- python - 将嵌套字典转换为字符串
- firebase - 设置文档及其所有子集合的权限
- r - 在重新验证所有输入后如何使用去抖动仅重绘图形
- java - 为什么 Java 的 URLEncoder 不会像 Python 的 urllib.parse.urlencode 那样生成?
- python - Python多线程不是并行执行的
- java - Google Play 已删除我的应用,但我在 Manifest 中找不到违规行?
- r - 为 guide_colorbar 设置默认特征
- vue.js - 在 vuejs 组件中使用刀片 @can 指令