【发布时间】: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 感到困惑。我读过this 和this 和this 但是,虽然有教育意义,但它们并没有处理数组和一个对象。我确实在这个项目中有下划线,但同样,我还没有发现任何我认为在这种情况下有用的东西。
我如何让它以一种满足我需要的方式运行?
【问题讨论】:
-
假设我们修复了
dataObject的语法,所以它是一个存储正确对象的正确数组:const results = checkArray.map(val => dataObject.findIndex(o => o.id == val)); -
我只是从
var_dump复制/粘贴并调整,老兄。足以传达这个想法。无论如何,我会考虑一下你的建议。
标签: javascript arrays object search