簡體   English   中英

如何返回從檢查數組匹配的 object 元素的索引

[英]How to return index of object element matched from a check array

我希望標題能恰當地表達我要解決的問題。 我需要做的是在 object 中搜索檢查數組中的匹配元素,並返回該匹配項的對象索引。 白衣:

const checkArray = ['18A38', '182B92', '85F33'];    //  these are the values to match
const dataOject = [
  0 => ['id'=>'853K83', 'isGO'=>false],             //  this is the object to search through
  1 => ['id'=>'85F33', 'isGO'=>true],
  2 => ['id'=>'97T223', 'isGO'=>true],
  3 => ['id'=>'18A38', 'isGO'=>false],
  4 => ['id'=>'182B92', 'isGO'=>true],
  ...
];

我需要做的是找到匹配的索引,然后我可以檢查是否設置了isGO標志。 這就是我在死胡同時所嘗試的:

results = checkArray.forEach(function(value, index){
  if (dataObject.findIndex(function(k=> k == value))) results.push(k);
    //  i know 'results.push(k)' is not right, but it's the essence of what i want.  :P
};

我期望results將是一個索引數組,然后我可以返回 go 並檢查dataObject是否設置isGO標志; results應如下所示:

results = [3, 1, 4];

但我對如何使findIndex正確完成感到困惑。 我讀過這個這個但是,雖然有教育意義,但他們沒有處理數組object。 我在這個項目中確實有下划線,但同樣,我還沒有發現任何我認為在這種情況下有用的東西。

我如何讓它以一種可以滿足我需要的方式運行?

與其返回索引,不如返回對象本身更容易?

const matchedObjects = dataObject.filter(object => checkArray.includes(object.id));

這將返回在您的checkArray中找到的所有具有id的對象。

將這些對象放在matchedObjects中,您可以遍歷它們並做任何您想做的事情。

類似的東西?

 const checkArray = ['18A38', '182B92', '85F33'] const dataOject = [ { id:'853K83', isGo:false }, { id:'85F33', isGo:true }, { id:'97T223', isGo:true }, { id:'18A38', isGo:false }, { id:'182B92', isGo:true } ]; const result = checkArray.map(val=>dataOject.findIndex(el=>el.id===val) ) console.log( JSON.stringify(result))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM