I have written a small function which iterates over a multi-dimensional object and should return the result, if a match is found between two variables.
Here is my function in full:
function getData(config) {
var code = "GB";
return Object.keys(config).forEach(function(country) {
if( Object.keys(config[country]).toString() === code ) {
return config[country][code]; // { data: "my correct matching data" }
}
});
}
Testing at the point of the deepest return
, I can see that config[country][code]
outputs the result I expect. Great! A match was found between config[country]
and code
so I want to return it.
However the function as a whole returns undefined
, but even setting the less deep return
to store the result as a variable, and checking the value of that, I also get undefined
. It seems though the match was found it is not returning correctly, see adjusted function below:
function getData(config) {
var code = "GB";
var result = Object.keys(config).forEach(function(country) {
if( Object.keys(config[country]).toString() === code ) {
return config[country][code]; // { data: "my correct matching data" }
}
});
return result; // undefined
}
Any ideas why the result is not returning fully? I'm guessing I'm missing a return somewhere.