如何返回从检查数组中匹配的对象元素的索引

问题描述 投票:0回答:1

我希望标题正确表达我要解决的问题。我需要做的是从检查数组中搜索匹配元素的对象,然后返回该匹配对象的索引。白衣:

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将是一个索引数组,然后我可以返回并检查dataObject中是否设置了isGO标志; results应该看起来像这样:

results = [3, 1, 4];

但是我很困惑如何使findIndex正确完成。我已经读过thisthisthis,但在进行教育时,它们并未处理数组and对象。我do在该项目中有下划线,但是,再次没有发现我认为在这种情况下有用的任何东西。

如何使它以给我所需的方式运行?

javascript arrays object search
1个回答
0
投票

代替返回索引,返回对象本身不是更容易吗?

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

将返回在id中找到具有checkArray的所有对象。

matchedObjects中有这些对象,您可以遍历它们并做您想做的任何事情。

© www.soinside.com 2019 - 2024. All rights reserved.