从对象中筛选属性的更干净的方式



我创建了一个函数来删除我告诉的属性

function trimProperties(data, properties) {
return data.map(o => {
Object.keys(o).forEach(k => {
if (properties.includes(k)) {
delete o[k];
} 
});
return o;
});
}

我的用例通常是这样的

let array = [
{
a: 'A',
b: 'B',
c: 'C'
},
{
a: 'A2',
b: 'B2',
c: 'C2'
}
]
// Remove every property 'b' or 'c' from the objects inside the array
trimProperties(array, ['b','c']);

我的问题很简单,我如何才能更快地实现这个函数,因为我的数组有时会变得很大,因为它是数据库访问的结果集

delete导致索引一直在重新计算,创建新数组会更快

let array = [
{
a: 'A',
b: 'B',
c: 'C'
},
{
a: 'A2',
b: 'B2',
c: 'C2'
}
]
function trimProperties(data, properties) {
let i = 0;
const result = []
while (i < data.length) {
var o = {};
Object.keys(data[i]).forEach(k => {
if (!properties.includes(k)) {
o[k] = data[i][k];
} 
})
i++;
if (Object.keys(o).length) {
result.push(o);
}
}

return result;
}
// Remove every property 'b' or 'c' from the objects inside the array
console.log(trimProperties(array, ['b','c']));

一行:

array.map(o => Object.fromEntries(Object.entries(o).filter(([k,v]) => !['b','c'].includes(k))))

演示:

const array = [
{
a: 'A',
b: 'B',
c: 'C'
},
{
a: 'A2',
b: 'B2',
c: 'C2'
}
];
const excluded = ['b','c'];
const filtered = array.map(o => Object.fromEntries(Object.entries(o).filter(([k,v]) => !excluded.includes(k))));
console.log(filtered)

最新更新