Get Javascript object value by key

前端 未结 3 1160
执笔经年
执笔经年 2020-12-05 16:45
var Array = [];

{\'DateOfBirth\' : \'06/11/1978\',
 \'Phone\' : \'770-786\',
 \'Email\' : \'pbishop@hotmail.com\' ,
 \'Ethnicity\' : \'Declined\' ,
 \'Race\' : \'Ot         


        
相关标签:
3条回答
  • 2020-12-05 17:18
    var myObject = {
      'DateOfBirth' : '06/11/1978',
      'Phone' : '770-786',
      'Email' : 'pbishop@hotmail.com' ,
      'Ethnicity' : 'Declined' ,
      'Race' : 'OtherRace'
    };
    
    // To get the value:
    var race = myObject.Race;
    //or
    var race = myArray[index].Race;
    
    0 讨论(0)
  • 2020-12-05 17:32

    Thats not an array, its an object. You want to do something like:

    var myObject = {
      'DateOfBirth' : '06/11/1978',
      'Phone' : '770-786',
      'Email' : 'pbishop@hotmail.com' ,
      'Ethnicity' : 'Declined' ,
      'Race' : 'OtherRace'
    };
    
    // To get the value:
    var race = myObject.Race;
    

    If the Objects are inside an array var ArrayValues = [{object}, {object}, ...]; then regular array accessors will work:

    var raceName = ArrayValues[0].Race;

    Or, if you want to loop over the values:

    for (var i = 0; i < ArrayValues.length; i++) {
        var raceName = ArrayValues[i].Race;
    }
    

    Good documentation for arrays can be found at the Mozilla Developer Network

    0 讨论(0)
  • 2020-12-05 17:39

    A few things here.

    You do not use Array, moreover, Array is actually what you can call when creating an Array, which you overwrite.

    Second, you have an object ({...}), but you do not assign it to something. Do you perhaps want to store it in a variable? (var obj = {...})?

    Thirdly, the last , should not be there since there aren't any more elements.

    If you have stored it in a variable, you can access it like obj.Race.

    0 讨论(0)
提交回复
热议问题