我有一个看起来像这样的对象数组
const data = [
{id: 1, locale: 'en'},
{id: 2, locale: 'nl'}
]
现在我正在尝试过滤掉数组中每个项目的locale属性(不要将其删除,只需将其过滤掉一次),因此我的数据理想地类似于:
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)
喜欢这个({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));