首页 > 解决方案 > Node.JS - filter() 仅在对索引进行硬编码时才有效

问题描述

尝试过滤和排列以获取与用户输入不匹配的对象。删除一本书。

用户输入: { title: 'WindFall', author: 'Jaime', body: 'another body of a body' }

过滤器正在查看的数组(来自 JSON 然后解析):

    [
  { title: 'title1', author: 'samson', body: 'this is the body' },
  {
    title: 'WindFall',
    author: 'Jaime',
    body: 'another body of a body'
  }
]

代码库:

function removeItem(item) {
try {
    const arrOfBooks = fs.readFileSync("./appendJSON.json").toString();
    const arrOfBooksParse = JSON.parse(arrOfBooks);

    const newArr = arrOfBooksParse.filter(item => {
        return arrOfBooksParse[item].title !== item.title;
    });
    console.log(newArr);

} catch (error) {
    console.log("There is nothing to remove");
}

}

因为我知道===用户输入的第二个对象,硬编码,

return arrOfBooksParse[1].title !== item.title;

工作,但return arrOfBooksParse[item].title !== item.title;没有。取而代之的是catchintry/catch熄灭。

标签: javascriptarraysnode.js

解决方案


item 它是数组中的对象。它没有索引。并且“item”从参数中覆盖“item”

固定代码:

function removeItem(item) {
    try {
        const arrOfBooks = fs.readFileSync("./appendJSON.json").toString();
        const arrOfBooksParse = JSON.parse(arrOfBooks);

        const newArr = arrOfBooksParse.filter((i) => i.title !== item.title);
        console.log(newArr);
    } catch (error) {
        console.log("There is nothing to remove");
    }
}

推荐阅读