【问题标题】:Filter property from multiple objects in array从数组中的多个对象中过滤属性
【发布时间】:2019-08-03 01:29:43
【问题描述】:

我有一个看起来像这样的对象数组

const data = [
    {id: 1, locale: 'en'},
    {id: 2, locale: 'nl'}
]

现在我正在尝试过滤掉数组中每个项目中的 locale 属性(不要永久删除它,只需过滤一次),因此我的数据理想情况下类似于:

const data = [
    {id: 1},
    {id: 2}
]

我试过了

  • 使用地图功能展开属性,但我不知道如何继续。

    this.translations.map(translation => {
        return { ...translation }
    })
    

【问题讨论】:

  • 其实我想排除其他值。因为可能有更多的价值

标签: javascript ecmascript-6 ecmascript-5


【解决方案1】:

您可以使用parameter destructuring 提取locale 并保留其他的:

const data = [
    {id: 1, locale: 'en'},
    {id: 2, locale: 'nl'}
]

const withoutLocale = data.map(({locale, ...rest}) => rest)

console.log(withoutLocale)

【讨论】:

  • 这是一个完美的解决方案。 +1
【解决方案2】:

这是使用map() reduce() filter() 的方法。此方法用于过滤掉动态键。

const data = [
    {id: 1, locale: 'en'},
    {id: 2, locale: 'nl'}
]
let filter = ['locale']
function removeKeys(keys,arr){
  return data.map(x => Object.keys(x).filter(b => !keys.includes(b)).reduce((ac,a) => ({...ac,[a]:x[a]}),{}))
}

console.log(removeKeys(filter,data));

【讨论】:

    【解决方案3】:

    这样做({key:value}) 带有返回地图

    适合您的情况

    this.translations.map(translation => {
        return ({['id']:translation.id })
    })
    

    工作示例

    const data = [{id: 1, locale: 'en'},{id: 2, locale: 'nl'}];
    
    var res = data.map(a=> ({['id']:a.id}));
    console.log(res)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-12
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 2021-07-07
      • 2020-04-21
      • 1970-01-01
      相关资源
      最近更新 更多