最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get Javascript object value by key - Stack Overflow

programmeradmin5浏览0评论
var Array = [];

{'DateOfBirth' : '06/11/1978',
 'Phone' : '770-786',
 'Email' : '[email protected]' ,
 'Ethnicity' : 'Declined' ,
 'Race' : 'OtherRace' , }

I need to access the 'Race' here.. how can i do it... Its an array which holds this data...

var Array = [];

{'DateOfBirth' : '06/11/1978',
 'Phone' : '770-786',
 'Email' : '[email protected]' ,
 'Ethnicity' : 'Declined' ,
 'Race' : 'OtherRace' , }

I need to access the 'Race' here.. how can i do it... Its an array which holds this data...

Share Improve this question edited Mar 25, 2014 at 18:36 brandonscript 72.9k35 gold badges172 silver badges237 bronze badges asked Jul 11, 2011 at 13:11 John CooperJohn Cooper 7,63133 gold badges83 silver badges102 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 14

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

var myObject = {
  'DateOfBirth' : '06/11/1978',
  'Phone' : '770-786',
  'Email' : '[email protected]' ,
  '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

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.

var myObject = {
  'DateOfBirth' : '06/11/1978',
  'Phone' : '770-786',
  'Email' : '[email protected]' ,
  'Ethnicity' : 'Declined' ,
  'Race' : 'OtherRace'
};

// To get the value:
var race = myObject.Race;
//or
var race = myArray[index].Race;
发布评论

评论列表(0)

  1. 暂无评论