0

I'm having a problem with accessing element inside an array. Here is a sample code:

var Core = {

    customNames: {
        '1':    [ 'Power Off' ],
        '21':   [ 'TV', 'Bedroom' ]
    },

    render: function() {
        $.each( Core.devices.result, function( i, obj ) {
            var name = Core.customNames[obj.idx][1] ? Core.customNames[obj.idx][1] : obj.Name;
        });
    }

};

obj.idx is a variable, let say with value 21. How to access 'Bedroom' in this case?

yosh
  • 1
  • 2
  • Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Taplar Dec 30 '19 at 22:14
  • devices doesn't seem to be defined anywhere. – Travis J Dec 30 '19 at 22:20
  • Hey Travis, it's just a part of the code, devices are defined elsewhere. – yosh Dec 30 '19 at 22:23

2 Answers2

0

try this in the render function!

render: function() {
        var that = this;
        $.each( this.devices.result, function( i, obj ) {
            var name = that.customNames[obj.idx][1] ? that.customNames[obj.idx][1] : obj.Name;
        });
    }

you have to set that because the scope inside the $.each changes!

Here is an example I tested and it worked:

var thing = {
    customNames: {
        '1':    [ 'Power Off' ],
        '21':   [ 'TV', 'Bedroom' ]
    },
    log: function(){
        console.log("This got logged inside here: " + this.customNames['21'][0]);
    }
}

thing.log()

Greetings!

J.Benda
  • 66
  • 4
0

Solved! It wasn't problem with accesing array element, but with incomplete customNames object. Proper code:

var name = Core.customNames[obj.idx] != undefined ? Core.customNames[obj.idx][0] : obj.Name;
yosh
  • 1
  • 2