0

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.

user1486133
  • 1,309
  • 3
  • 19
  • 37
  • 1
    `forEach` always returns `undefined`. – Teemu Feb 11 '20 at 12:59
  • You should use `find` instead of `forEach`. It's better suited to your use case. – igg Feb 11 '20 at 13:00
  • `Array.prototype.forEach` returns `undefined`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach and `Object.keys` returns an `Array`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys – messerbill Feb 11 '20 at 13:01

0 Answers0