0

I am having conceptual Javascript issues while returning Object from functions. Can someone point out what am I doing wrong here?

var productsPartsObj = {
  layers: ['toe', 'base', 'shaft'],
  layer: [
    {
      name: 'toe',
      height: 75,
      width: 78,
      coords: {
        x: 20,
        y: 120
      }
    }
  ]
}

var coords = {};
coords = (function() {
  productsPartsObj.layer.forEach(function(layerObj){
    if ( layerObj.name === "toe" ) {
      return layerObj.coords;
    }
  })
})()

console.log(coords); //logs undefined

2 Answers 2

6

You are returning from the forEach callback, not from the immediately-executed function expression. You could do this instead (assuming you know there will only ever be one element of the layer array with a name matching the value in question:

var coords = (function() {
  return productsPartsObj.layer.filter(function(layerObj){
      return layerObj.name === "toe";
  })[0].coords;
})();

Notice that there are 2 return statements - the first one returns from the IIFE, and the second returns from the filter callback.

Also notice that I've moved the var keyword into this statement. There is no point assigning an empty object to coords and then simply overwriting it.

Sign up to request clarification or add additional context in comments.

Comments

0

Your anonymous function is not returning any value.

var productsPartsObj = {
    layers : ['toe', 'base', 'shaft'],
    layer : [{
                name : 'toe',
                height : 75,
                width : 78,
                coords : {
                    x : 20,
                    y : 120
                }
            }]
}

var coords = {};
coords = (function() {
    var x;
    productsPartsObj.layer.forEach(function(layerObj) {
                if (layerObj.name === "toe") {
                    x = layerObj.coords;
                }
            })
    return x;
})()

console.log(coords);

Else set the coords value directly using

var coords = {};
(function() {
    productsPartsObj.layer.forEach(function(layerObj) {
                if (layerObj.name === "toe") {
                    coords = layerObj.coords;
                }
            })
})()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.