-1

So, I have following js :

var NAMES = {

'185' : {
        'FIRST'     : 'first',
        'MIDDLE'    : 'middle',
        'LAST'      : 'last'
    }
};

for (var j = 0; j < (id.length); j++) {         
     var uDATA_ID = id[j]; //string
     var uDATA_OBJ = JSON.parse(uDATA_ID);  //converted to object            
     if (uDATA_ID == NAMES.uDATA_OBJ){
        alert("Somethings happening");                               
     }
}

So, I get a string of ids from php. I need to check if this number is available in the object variable.

However, I am having a hard time making it work.

Could someone help me out?

Thanks

Steve Kim
  • 5,293
  • 16
  • 54
  • 99
  • `uDATA_ID == NAMES.uDATA_OBJ` doesn't make much sense to me. What is supposed to do? – Felix Kling Feb 05 '16 at 01:09
  • Sp. `uDATA_ID` has a value of "185". I am trying to see if the top array contains the same value. – Steve Kim Feb 05 '16 at 01:14
  • Duplicate of [Dynamically access object property using variable](http://stackoverflow.com/q/4244896/218196) and [check if object property exists - using a variable](http://stackoverflow.com/q/11040472/218196) – Felix Kling Feb 05 '16 at 01:15

1 Answers1

1

To use a variable to access an object field, use the [field] syntax instead of the .field syntax:

 var data = NAMES[uDATA_ID]

If that field is missing, it will return undefined (which you can then check for)

 if (data) {   // assumes you don't want `false` or `0`.
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Thanks. That was bit frustrating as some of the old answered from SO had different syntax format. Thanks for the clarification. Thanks! – Steve Kim Feb 05 '16 at 01:09
  • Just a quick question. How would I check if the "top" array contains the same object? (For example, `if (typeof uDATA_ID == NAMES[uDATA_OBJ])`)? – Steve Kim Feb 05 '16 at 01:12
  • http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects – Thilo Feb 05 '16 at 01:21