首页 > 解决方案 > 从对象数组中提取一些属性

问题描述

如何从对象数组中提取一些属性,例如没有 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]}

标签: javascriptecmascript-6

解决方案


您可以使用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']))


推荐阅读