【问题标题】:How to return index of object element matched from a check array如何从检查数组中返回匹配的对象元素的索引
【发布时间】:2020-08-24 15:36:33
【问题描述】:

我希望标题能恰当地表达我要解决的问题。我需要做的是从检查数组中搜索一个匹配元素的对象并返回该匹配的对象索引。到白衣:

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 但是,虽然有教育意义,但它们并没有处理数组一个对象。我确实在这个项目中有下划线,但同样,我还没有发现任何我认为在这种情况下有用的东西。

我如何让它以一种满足我需要的方式运行?

【问题讨论】:

  • 假设我们修复了dataObject 的语法,所以它是一个存储正确对象的正确数组:const results = checkArray.map(val => dataObject.findIndex(o => o.id == val));
  • 我只是从var_dump 复制/粘贴并调整,老兄。足以传达这个想法。无论如何,我会考虑一下你的建议。

标签: javascript arrays object search


【解决方案1】:

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

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

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

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

【讨论】:

  • 呃......是的......这太明显了,我想把头撞到桌子上......?
  • 温柔点?
  • 我。谢谢。这工作得很好。实际上,比我知道的更完美。
【解决方案2】:

类似的东西?

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))

【讨论】:

  • 谢谢。这很好。它完全针对我正在寻找的东西。
  • 很奇怪。我确实做到了。在这里,我再次点击。你值得投票。
猜你喜欢
  • 2013-02-19
  • 2020-06-01
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 2015-05-27
  • 2018-04-14
  • 2018-12-29
  • 1970-01-01
相关资源
最近更新 更多