javascript - 遍历对象并删除特定属性或使其未定义
问题描述
我有这个控制器功能:
exports.getBooks = async (req, res) => {
try {
const { ...books } = await Book.find();
} catch (err) {
console.log(err);
}
};
这是书籍对象的当前输出示例:
{
'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);
推荐阅读
- mysql - docker compose 无法附加到 mysql windows 的端口
- python - pygame中的音量控制
- variables - 可变通过动态管道
- python - Safari Private 浏览器上的 403 CSRF 验证失败
- c# - C# 从 DotNet EXE 安装程序中捕获进度
- javascript - 使用 Javascript 提升概念,我尝试了以下方法。我不确定为什么选择了 name 变量而不是年龄
- linux - 为什么执行 (False) if 语句中的部分代码?
- excel - 是否可以将 .CopyFromRecordset 中的数据粘贴到特定的单元格中
- sql - CONVERT 函数没有我在 SQL 2008 中需要的日期时间的正确格式
- javascript - 使用javascript es6从包含唯一ID和嵌套数组的多个对象数组中获取公共数据