简体   繁体   中英

Object.keys() and find

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.

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) 

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