在我尝试对以下数据使用ES6 .find
时,我很难理解为什么会出现错误。我试图获取身份证号码为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'}
}
我试过
const category = categories.find(function (category) { return category.id === 3; }
console.log(category)
和
const category = categories.filter(category => category.id === 3)
console.log(category)
感谢任何帮助。
答案 0 :(得分:6)
Array.filter()
和 Array.find()
适用于不在对象上的数组。
您需要将数据更改为
对象数组[
{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'}
]
<强>样本强>
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)
&#13;