首页 > 解决方案 > 遍历对象并删除特定属性或使其未定义

问题描述

我有这个控制器功能:

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 解决方案。

谢谢。

标签: javascript

解决方案


您可以使用Object.entriesreduce来达到预期的效果。

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);


推荐阅读