[英]Iterate through objects and delete specific properties or make them undefined
我有这个 controller function:
exports.getBooks = async (req, res) => {
try {
const { ...books } = await Book.find();
} catch (err) {
console.log(err);
}
};
这是书籍 object 的当前 output 示例:
{
'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
},
}
现在,在我将 object 发送给客户端之前,我想从每个内部 object 中删除_id和__v属性。
使_id和__v属性未定义也可以。
我已经看到了一些使用 lodash 的解决方案,我正在寻找一个纯 javascript 解决方案。
谢谢。
您可以使用Object.entries和reduce来达到预期的效果。
const books = { "0": { _id: "60c098ef9855786e7419201d", author: "JK 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.