The code works with a simple foreach function, but not with a find method. Here is the forEach code:
getItemById: function (id) {
let found = null;
data.items.forEach(item => {
if (item.id === id) {
found = item;
}
});
return found;
}
Here is the code with a find mehtod:
getItemById: function (id) {
let item = data.items.find(item => {
item.id === id;
});
return item;
}
Why doesn't work the code with the find method?
also here is the array of the objects:
const data = {
items: [
{ id: 0, name: 'Steak Dinner', calories: 1200 },
{ id: 1, name: 'Sausage', calories: 1100 },
{ id: 2, name: 'Eggs', calories: 200 },
],
currentItem: null,
totalCalories: 0,
}
The find expects a predicate function as a callback and return the value that satisfy the condition. If you won't return then undefined will return by default and undefined is considered as a falsy value.
You are not returning anything from the find function. find will not consider a match if predicate function won't return true. There is not a single match that returns true in any case because all values returned by find is undefined
return item.id === id.
const data = {
items: [
{ id: 0, name: "Steak Dinner", calories: 1200 },
{ id: 1, name: "Sausage", calories: 1100 },
{ id: 2, name: "Eggs", calories: 200 },
],
currentItem: null,
totalCalories: 0,
};
const obj = {
getItemById: function (id) {
let item = data.items.find((item) => {
return item.id === id;
});
return item;
},
};
console.log(obj.getItemById(0));
getItemById: function (id) {
return data.items.find(item => item.id === id);
}
You don't have to use "{" and ";" in data.items.find() method. Because,the find is a predicate function
You're not returning the boolean inside find's callback
let item = data.items.find(item => {
return item.id === id;
});