簡體   English   中英

Node.JS - filter() 僅在對索引進行硬編碼時才有效

[英]Node.JS - filter() only works when hard coding in a index

嘗試過濾和排列以獲取與用戶輸入不匹配的對象。 刪除一本書。

用戶輸入: { 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");
}

}

由於我知道第二個 object ===用戶輸入,硬編碼,

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

有效但return arrOfBooksParse[item].title.== item;title; 才不是。 相反, try/catch catch的 catch 會觸發。

項目是數組中的 object。 它沒有索引。 並且“item”會覆蓋 arguments 中的“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");
    }
}

嘗試這樣的事情:

const newArr = arrOfBooksParse.filter(book => {
    return book.title !== item.title;
});

您只需要為這本書命名(在過濾器中)與傳入的item不同。

回調中的item是實際項目。 不是索引。 使用該項目在數組中查找會導致您陷入困境。

filter方法不是在數組中查找值,而是為您提供元素。 您需要做的只是重命名您的參數之一,並使用filter回調傳遞給您的項目。

看起來像這樣:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM