【问题标题】:Delete Function using .filter Method使用 .filter 方法删除函数
【发布时间】:2020-11-25 17:47:12
【问题描述】:

我正在创建一个笔记应用程序,但我的 deleteNote 功能卡住了。我需要使用 .filter 方法删除带有分配 ID 的注释并保留与该 ID 无关的注释。到目前为止,这是我的代码。

const fs = require("fs"); 
const util = require("util");
// returns a unique ID for our returns 
const uuidv1 = require("uuid/v1");

// creates a promified version of fs.readfile and writefile
const readFileAsync = util.promisify(fs.readfile); 
const writeFileAsync = util.promisify(fs.writefile);

class Store {
    read() {
        return readFileAsync("./db/db.json", "utf8");
    }
    write(note) {
        return writeFileAsync("./db/db.json", JSON.stringify(note)); 
    }
    getNotes() {
        return this.read().then(notes => {
            let parsedNotes; 
        try {parsedNotes = [].concat(JSON.parse(notes))}
        catch (err) {
            parsedNotes = [];
        }
        return parsedNotes;
        })
    }
// example of destructuring -- im taking the title, text string and destructuring it to add a unique id. 
    addNote(note) {
        const {title, text} = note;
        const newNote = {title, text, id: uuidv1()};
        return this.getNotes()
        .then(notes => [...notes, newNote]);
        .then(updatedNotes => this.write(updatedNotes));
        .then(() => newNote);
    } 

// delete note is going to take in an id and use a .filter to only keep the notes that do not include that id. 

    deleteNote() {
        
    }

} 

module.exports = new Store();

【问题讨论】:

    标签: javascript node.js api require


    【解决方案1】:

    你已经知道你在过滤,所以就去做吧:

    deleteNote(id) {
        return this.getNotes()
            .then(notes => notes.filter(note => note.id !== id))
            .then(updatedNotes => this.write(updatedNotes));
    }
    

    【讨论】:

      【解决方案2】:

      试试这个,其中包括返回已删除的笔记。

        async deleteNote(id) {
          const notes = await this.getNotes();
          const filtered = notes.filter((note) => note.id !== id);
          await this.write(filtered);
          const deleted = notes.filter((note) => note.id === id);
          return deleted;
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-20
        • 2019-07-04
        • 2017-08-23
        • 2020-03-27
        • 1970-01-01
        • 2018-06-26
        • 2015-05-05
        • 2020-11-29
        相关资源
        最近更新 更多