i hope the title is properly expressive of the problem i'm trying to solve. what i need to do is search an object for a matching element from a check array and return the object's index of that match. to whit:
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],
...
];
what i need to do is find the matching index so i can then check if the isGO
flag is set. this is what i was trying when i dead-ended:
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
};
what i am expecting is that results
will be an array of indexes that i can then go back and check the dataObject
for set isGO
flags; results
should look like this:
results = [3, 1, 4];
but i'm stumped on how to make the findIndex
complete properly. i've read this and this and this but, while educational, they aren't dealing with an array and an object. i do have underscore in this project, but, again, haven't found anything that i comprehend as useful in this scenario.
how do i get this to run in a way that gives me what i need?
Instead of returning the indexes, isn't it easier to return the objects itself?
const matchedObjects = dataObject.filter(object => checkArray.includes(object.id));
That will return all objects having id
found in your checkArray
.
Having these objects in matchedObjects
, you can iterate through them and do whatever you wish.
something like that?
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.