简体   繁体   中英

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

Attempting to filter and array to get back objects that do not match with the user's input. Removing a book.

user's input: { title: 'WindFall', author: 'Jaime', body: 'another body of a body' }

array the filter is looking through (came from JSON then parsed):

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

Codebase:

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

}

Since I know the 2nd object === the user input, hard coding,

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

works but return arrOfBooksParse[item].title.== item;title; does not. Instead the catch in try/catch fires off.

item it is object from array. its no index. and "item" overrides "item" from arguments

fixed code:

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

Try something like this instead:

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

You just need to name the book something different (in the filter) than the item passed in.

item in the callback is the actual item. Not the index. Using the item to lookup in the array is causing you to fall into the catch.

Instead of looking up the value in the array, the filter method provides you with the element. What you need to do is just rename one of your parameters, and use the item passed to you by the filter callback.

that would look something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM