原始数据结构
const myArray = [
{
workFootageId: "1302466415638351875",
workReportId: "1302384118092271623",
workReportTime: "1692259200000",
},
{
workFootageId: "1302466415638351875",
workReportId: "1302384118092271623",
workReportTime: "1692259200000",
},
];
封装方法
function removePropertyFromArray(array, property) {
return array.map(obj => {
const { [property]: removedProperty, ...rest } = obj;
return rest;
});
}
去掉多个字段
function removePropertiesFromArray(array, properties) {
return array.map(obj => {
const newObj = { ...obj };
properties.forEach(property => {
delete newObj[property];
});
return newObj;
});
}
使用
在上面的示例中,我们定义了一个数组 myArray,然后使用 removePropertyFromArray 函数去掉了其中的 workFootageId 属性,最后打印出新的数组。输出结果与之前相同:
const newArray = removePropertyFromArray(myArray, 'workFootageId');
console.log(newArray);
多个字段时
const propertiesToRemove = ['workFootageId', 'workReportId'];
const newArray = removePropertiesFromArray(myArray, propertiesToRemove);
得到结果
[
{
workReportId: "1302384118092271623",
workReportTime: "1692259200000",
},
{
workReportId: "1302384118092271623",
workReportTime: "1692259200000",
},
]