Question

I have a third party function which returns an object

abc.xyz() --> this returns an object containing many objects,strings,boolean & arrays . Basically JSON style 
object. 

I am iterating through this object to get only the objects inside this object & that object should have a key named "apple" . Once I locate that object, I'm putting the key into a variable named "index" & then using that variable "index" to get the object that I want using

abc.xyz().index // This should ideally return an object, but this is undefined. Why?

My code below.

var pa= abc.xyz();
    var index; 
    for(var key in pa){
        if (pa.hasOwnProperty(key)) {
            var obj = pa[key];

            for(var prop in obj){
                if(obj.hasOwnProperty(prop)){
                    if(typeof obj === 'object'){ 
                        if( prop == "apple"){
                            index = key;
                        }
                    }
                }
            }
         }
    } 

    el.appendChild(ul(pa.index)); // though I get the correct index when i  
        console.log(index) but why is pa.index undefined? 

If I don't use index variable & I directly say pa.k where k is the value of index , it works. then why wont pa.index work?

Was it helpful?

Solution

Here's an example that illustrates how the two different syntaxes for property access work in javascript:

var o = {
  index: 'this is index',
  APPLE: 'this is APPLE'
};
var index = 'APPLE';
console.log(o.index);     // --> this is index
console.log(o[index]);    // --> this is APPLE  *
console.log(o['index']);  // --> this is index

the one marked with a * is the one you should be using in this case. This form looks for a property of o, whose name matches the value contained in the variable index. The other two forms just look for a property named "index". So the final line of your example should be:

el.appendChild(ul(pa[index]));   // assuming that `el` and `ul()` were both
                                 // defined appropriately elsewhere in your 
                                 // script.

Also... it seems that your logic might be simplified substantially. Consider the following:

var pa = abc.xyz();
var result; 
for(var key in pa){
  if (pa.hasOwnProperty(key)) {
      var obj = pa[key];
      if(obj.hasOwnProperty("apple")) {
          result = obj;
      }
   }
}
el.appendChild(ul(result));

OTHER TIPS

pa.index looks for the key named "index"

To look up the key for the value of index, you need to use pa[index] - no period, just the brackets.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top