Reputation: 2118
Struggling to understand why I get an error when I try to use ES6 .find
on this data below. I'm trying to get the record with id number 3.
{
{id:10,title:'Dairy & Eggs'}
{id:7,title:'Laundry & Househo,}
{id:9,title:'Bakery'}
{id:8,title:'Fresh Food'}
{id:4,title:'Frozen Food'}
{id:6,title:'Health & Beauty'}
{id:3,title:'Food Cupboard'}
{id:5,title:'Drinks'}
{id:2,title:'Chilled Food'}
}
I tried
const category = categories.find(function (category) { return category.id === 3; }
console.log(category)
and
const category = categories.filter(category => category.id === 3)
console.log(category)
Any help is appreciated.
Upvotes: 0
Views: 98
Reputation: 222552
Array.filter()
and Array.find()
works over array not on object.
Either you need to change your Data to Array of Objects as
[
{id:10,title:'Dairy & Eggs'},
{id:7,title:'Laundry & Househo'},
{id:9,title:'Bakery'},
{id:8,title:'Fresh Food'},
{id:4,title:'Frozen Food'},
{id:6,title:'Health & Beauty'},
{id:3,title:'Food Cupboard'},
{id:5,title:'Drinks'},
{id:2,title:'Chilled Food'}
]
DEMO
var categories = [
{
"id": 10,
"title": "Dairy & Eggs"
},
{
"id": 7,
"title": "Laundry & Househo"
},
{
"id": 9,
"title": "Bakery"
},
{
"id": 8,
"title": "Fresh Food"
},
{
"id": 4,
"title": "Frozen Food"
},
{
"id": 6,
"title": "Health & Beauty"
},
{
"id": 3,
"title": "Food Cupboard"
},
{
"id": 5,
"title": "Drinks"
}
];
const category = categories.filter(category => category.id === 3) ;
console.log(category)
Upvotes: 6