![](/img/trans.png)
[英]How can I convert an array of objects to array with a unique id in javascript?
[英]How can I search through an array of objects for a unique id?
我有一個對象數組和一個唯一的ID。 我想在對象數組中搜索與唯一ID相匹配的對象實例,但是我不確定如何開始使用它。
idToSearchfor = 2
arrayToBeSearched = [{content: 'string', id: 1}, {content: 'string', id: 2}, {content: 'string', id: 3}]
這就是Array.prototype.find()
目的,假設您確定自己不會有多個匹配項( find
僅返回第一個匹配項):
let idToSearchfor = 2; const arr = [{content: 'string', id: 1}, {content: 'string', id: 2}, {content: 'string', id: 3}] console.log(arr.find(x=>x.id===idToSearchfor));
否則(可能有多個匹配項),請使用Array.prototype.filter()
:
let idToSearchfor = 2; const arr = [{content: 'string', id: 1}, {content: 'string', id: 2}, {content: 'string', id: 3}] console.log(arr.filter(x=>x.id===idToSearchfor));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.