Object.keys()并查找

时间:2018-05-01 16:44:55

标签: reactjs typescript ecmascript-6

在我尝试对以下数据使用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)

感谢任何帮助。

1 个答案:

答案 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'}
]

<强>样本

&#13;
&#13;
 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;
&#13;
&#13;