从数组中的多个对象中过滤 属性
Filter property from multiple objects in array
我有一组看起来像这样的对象
const data = [
{id: 1, locale: 'en'},
{id: 2, locale: 'nl'}
]
现在我正在尝试过滤掉数组中每个项目的语言环境属性(不是永久删除它,只是过滤掉它一次) ,所以我的数据理想情况下类似于:
const data = [
{id: 1},
{id: 2}
]
我试过了
使用映射函数展开属性,但我不知道如何继续这个。
this.translations.map(translation => {
return { ...translation }
})
您可以使用 parameter destructuring 提取 locale
并保留其他的:
const data = [
{id: 1, locale: 'en'},
{id: 2, locale: 'nl'}
]
const withoutLocale = data.map(({locale, ...rest}) => rest)
console.log(withoutLocale)
使用 return 地图
这样做 ({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)
这是使用 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));
我有一组看起来像这样的对象
const data = [
{id: 1, locale: 'en'},
{id: 2, locale: 'nl'}
]
现在我正在尝试过滤掉数组中每个项目的语言环境属性(不是永久删除它,只是过滤掉它一次) ,所以我的数据理想情况下类似于:
const data = [
{id: 1},
{id: 2}
]
我试过了
使用映射函数展开属性,但我不知道如何继续这个。
this.translations.map(translation => { return { ...translation } })
您可以使用 parameter destructuring 提取 locale
并保留其他的:
const data = [
{id: 1, locale: 'en'},
{id: 2, locale: 'nl'}
]
const withoutLocale = data.map(({locale, ...rest}) => rest)
console.log(withoutLocale)
使用 return 地图
这样做({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)
这是使用 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));