简体   繁体   中英

Get a property value from an object and assign it to a variable in javascript

I have this object and a I need to get the value of property name to assign it to a variable so that I can use it for each option in a menu. Here is the data returned:

“parentArrayOfObjects”: [
    {
     “data”: {
        “current”: {
           “id”: 0, 
           “name”: “Winter”
         }   
      }
    },
    {
      “data”: {
         “current”: {
            “id”: 0, 
            “name”: “Spring”
          }   
        }
     }    
 ]

Using the above, I'm getting the same value for the data.current.name property for each menu at index 0, and that isn't what I want. Please tell me what I'm doing wrong. Thanks.

// returns same name in all menus
var getCurrentChildPropertyName = (function(){
    for (var value in parentArrayOfObjects) {
         var currentChildProperty=parentArrayOfObjects[value].data.current;
         if( currentChildProperty !== null){                                                        
             return currentChildProperty.name;
         }
    }
})();

// returns same name in all menus
var getCurrentChildPropertyName = (function(){
    for ( var i = 0; i < parentArrayOfObjects.length; i++) {
          var currentChildProperty = parentArrayOfObjects[i].data.current;
          if( currentChildProperty !== null){
              return currentChildProperty.name;
          }
     }
})();


// Use different returned name in each menu (ExtJs3)
     dataStore.insert(0, [new Ext.data.Record({
                 id: 0,                                                    
                 name: getCurrentChildPropertyName
     })
const x = {'parentArrayOfObjects': [
  {
   'data': {
      'current': {
         'id': 0,
         'name': 'Winter'
       }
    }
  },
  {
    'data': {
       'current': {
          'id': 0,
          'name': 'Spring'
        }
      }
   }
]}

const results = x.parentArrayOfObjects.map((item) => item.data.current.name);

console.log(results); //[ 'Winter', 'Spring' ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM