【问题标题】:Extract from array of objects some properties从对象数组中提取一些属性
【发布时间】:2018-06-08 11:55:20
【问题描述】:

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

【问题讨论】:

  • without for loop, with map or filter?这是什么意思?
  • 尝试使用.reduce(),因为您正在将多个对象的数组“缩减”为一个对象的摘要。
  • 为什么是-4?这个问题有什么问题?
  • @Grigor 因为 Nina 对所有没有添加他们已经尝试过的内容的人投了反对票。
  • 什么?没看懂,求简单

标签: javascript ecmascript-6


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以通过使用键映射值来采取动态方法。

    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']));

    【讨论】:

      猜你喜欢
      • 2019-04-16
      • 2010-11-10
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 2015-08-22
      • 2023-01-27
      • 2017-10-25
      相关资源
      最近更新 更多