sltdev
sltdev

Reputation: 459

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.

Upvotes: 0

Views: 136

Answers (3)

Francisco Garcia
Francisco Garcia

Reputation: 376

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

Upvotes: 0

Dzmitry Shatsera
Dzmitry Shatsera

Reputation: 36

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

Upvotes: 1

Davin Tryon
Davin Tryon

Reputation: 67316

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.

Upvotes: 0

Related Questions