I want to be able to use getValue and iterate myObject keys to get the key value "f" if i input any variable.
result = "f";
Or
result = " g";
const myObject = {
"f": [1, 2, 3, 4, 5],
"g": [6, 7, 8, 9, 10]
};
let getValueOne = 1;
function getKeyByValue() {
for (let i = 0; i < myObject[value].length; i++) {
result = myObject.key[i];
if (i === getValueOne) {
console.log(result);
}
}
}
3
Answers
You mean find the key which array contains the value?
Alternative
Using a lookup table (inspired by vitaly-t’s answer)
This is assuming unique values across all arrays
@mplungjans answer using
Array.find
If the speed of accessing the same object is important, then it is best to create a
Map
from that object first, and then you can retrieve each value instantly:And if some values are not unique across arrays, each later value will be overriding the former one.