从数组中的多个对象过滤属性

问题描述 投票:3回答:3

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

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

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

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

I've tried

  • 使用map函数展开属性,但我仍然坚持如何继续这个。 this.translations.map(translation => { return { ...translation } })
javascript ecmascript-6 ecmascript-5
3个回答
10
投票

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

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

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

console.log(withoutLocale)

0
投票

喜欢这个({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)

0
投票

以下是使用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));
© www.soinside.com 2019 - 2024. All rights reserved.