0

Im am working with some code from another developer and came across something I have not seen before. The basic functionality of the code is to look for a piece of data in an object within an object. The object format is theObj {key:Object, key:Object,...}, the data being searched for is stored in 2 variables inkey,lookfor.

$.each(theObj, function(m,n){
    if(typeof(n['data'][inkey]) != "undefined" && n['data'][inkey] !== null) {
        if(n['data'][inkey][lookfor] == 1){..}
    }
});

What does the ['data'] do?

LouieV
  • 1,032
  • 2
  • 15
  • 28

3 Answers3

4

It is looking for a property data in the object n - n['data'] is the same as n.data

karthikr
  • 97,368
  • 26
  • 197
  • 188
2

n['data'] is the same as n.data but sometime it's useful to use brackets like when you need to use a variable like n['data'][inkey].

Btw you or him should use n.data.hasOwnProperty(inkey) instead of typeof(n['data'][inkey]) != "undefined"

You could write it like that :

$.each(theObj, function(m,n){
    if(n.data.hasOwnProperty(inkey) && n.data[inkey] !== null) {
        if(n.data[inkey][lookfor] == 1){..}
    }
});
TecHunter
  • 6,091
  • 2
  • 30
  • 47
1

data is the property name or key in the object. So n['data'] would return the property value for the property name data in object n.

And what you have is an Object not an Array.

Array contains list of elements with integer based index, where else Object contains list of elements with key based index.

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134