Home > Back-end >  A better way to test a match when iterating over multiple objects in an array
A better way to test a match when iterating over multiple objects in an array

Time:09-07

I am having trouble with a small function I have written in that I cannot get the value to return properly. I am wondering if there is a better way to do this than using a .forEach loop.

    var userSelectedBook = { id: 1234 };
    var bookList = [
        {
            id: 5678,
            color: "blue"
        },
        {
            id: 1234,
            color: "red"
        }
    ];
    
    function getBookColor(bookList, userSelectedBook) {
      const color = bookList.forEach(book => {
        if (book.id === userSelectedBook.id) {
          return book.color;
        }
      });
      return color;
    }

In the above case, when I call getBookColor() I would expect to receive the response "red" because I am passing the userSelectedBook where the ID is 1234.

However I only get undefined even though putting a console log within the if statement does show the correct color.

CodePudding user response:

forEach is a void function ( always returns undefined ), you need to use find instead.

function getBookColor(bookList, userSelectedBook) {
  return bookList.find(book => book.id === userSelectedBook.id)?.color;
}

CodePudding user response:

const bookList = [{id: 5678,color: "blue"},{id: 1234,color: "red"}];

function getColorForId(list,id){
 return list.find(b=>b.id==id)?.color ?? "none";
}

['5678', 1234, 12345].forEach(t=>
 console.log(`The book ${t} is ${getColorForId(bookList,t)}.`)
);

  • Related