遍历对象并删除特定属性或使其未定义



我有这个控制器功能:

exports.getBooks = async (req, res) => {
try {
const { ...books } = await Book.find();
} catch (err) {
console.log(err);
}
};

这是books对象的当前输出示例:

{
'0': {
_id: 60c098ef9855786e7419201d,
author: 'J.K. Rowloing',
title: 'Harry Potter',
date: 1999-02-02T00:00:00.000Z,
__v: 0
},
'1': {
_id: 60c09b785f0d717012a72e3a,
author: 'Tolkin',
title: 'Lord of the Rings',
date: 2009-01-01T00:00:00.000Z,
__v: 0
},
}

现在,在将对象发送到客户端之前,我想从每个内部对象中删除_id__v属性。

未定义_id__v属性也可以。

我已经看到了一些使用lodash的解决方案,我正在寻找一个纯javascript解决方案。

谢谢。

您可以使用Object.entries和reduce来获得所需的结果。

const books = {
"0": {
_id: "60c098ef9855786e7419201d",
author: "J.K. Rowloing",
title: "Harry Potter",
date: "1999-02-02T00:00:00.000Z",
__v: 0,
},
"1": {
_id: "60c09b785f0d717012a72e3a",
author: "Tolkin",
title: "Lord of the Rings",
date: "2009-01-01T00:00:00.000Z",
__v: 0,
},
};
const result = Object.entries(books).reduce((acc, [key, value]) => {
const { _id, __v, ...rest } = value;
acc[key] = rest;
return acc;
}, {});
console.log(result);

最新更新