1

I'm having an issue setting my data object's value in my for loop.

// data object
var data = {
  title: '',
  x: {
    something: 'test',
    someVar: ''
  },
  y : {
    something: '',
    someVar: ''
  },
  dots: []
}

For example, I want to set (or update) data.x.something = "tested"; I can console.log and see the updated value as tested. However, in my for loop it creates an error:

    for(var i = 0, len = data.length; i < len; i++) {
      data.x.something = "x";
      console.log('data.x.something', data.x.something);
      // log says "Uncaught TypeError: Cannot set property 'something' of undefined". How come I can't set the var inside my for loop? 
    }

Any suggestions? Thanks.

chatu
  • 305
  • 5
  • 13
  • 1
    Two things: your `data` object apparently does not expose a `length` property, and you're using an unquoted reserved word (`else`) as a property name, which is a syntax error. – Frédéric Hamidi Mar 13 '13 at 14:04
  • The TypeError is quite descriptive: `data.x` is `undefined`, you have to set it to an object before assigning properties on it – Bergi Mar 13 '13 at 14:08
  • When debugging, what is the value of 'x' inside your for loop? It looks it is undefined – David L Mar 13 '13 at 14:09
  • @DavidL data.x is undefined. – ialphan Mar 13 '13 at 14:12
  • @chatu Why don't you post more code? It's difficult to tell what is going on from the limited sample you have here. – David L Mar 13 '13 at 14:14
  • @ialphan yes data.x is undefined. – chatu Mar 13 '13 at 14:17
  • @DavidL I just want to set my object: data.x.something = "tested"; inside my for loop (but for some reason it becomes undefined). I can only set it outside of the for loop. – chatu Mar 13 '13 at 14:19

1 Answers1

0

Working jsFiddle with the below code is HERE

First of all, your data object is poorly designed. If you want to iterate over it, then it means it holds x objects of the same type.

 var data = [
    {// first object with the properties.
      title: '',
      x: {
        something: 'test',
        someVar: ''
      },
      y : {
        something: '',
        someVar: ''
      },
      dots: []
    }, {// second object with same properties
      title: '',
      x: {
        something: 'test2',
        someVar: ''
      },
      y : {
        something: '',
        someVar: ''
      },
      dots: []
    }
];

Second, that's not how you iterate through an object. That's because a JavaScript object doesn't have a length property and that is not the proper way to iterate over an object. If you need a collection to hold n objects of the type k(with a specific set of properties), then use an array, otherwise you will need more useless nesting. See my answer to this question about arrays and objects in JS.

    for (var i = 0, len = data.length; i < len; i++) {
        data[i].x.something = "x";
        console.log(data[i].x.something);
    };
Community
  • 1
  • 1
flavian
  • 28,161
  • 11
  • 65
  • 105