How to access javascript object without "name" - Stack Overflow

var text = '{ "employees" : [' +'{ "id": 999, "username":

var text = '{ "employees" : [' +
'{ "id": 999, "username": "Batman" } ]}';

obj = JSON.parse(text);
var id = obj.employees[0].id;

Question is, how to access as in example above id, from javascript object? In example above it has "name" to gain access to id, which is employees. But real life example below i don't have "name" to use to gain id value.

var text = '{ "" : [' +
'{ "id": 999, "username": "Batman" } ]}';

obj = JSON.parse(text);
var id = obj.**WHAT TO PUT HERE TO ACCESS-->**.id;
var text = '{ "employees" : [' +
'{ "id": 999, "username": "Batman" } ]}';

obj = JSON.parse(text);
var id = obj.employees[0].id;

Question is, how to access as in example above id, from javascript object? In example above it has "name" to gain access to id, which is employees. But real life example below i don't have "name" to use to gain id value.

var text = '{ "" : [' +
'{ "id": 999, "username": "Batman" } ]}';

obj = JSON.parse(text);
var id = obj.**WHAT TO PUT HERE TO ACCESS-->**.id;
Share Improve this question asked Jun 9, 2015 at 22:17 JohnJohn 451 silver badge6 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 7

you can access for empty string as a key and remember that is a array inside, use the item 0

obj[''][0].id

You can avoid this situation by using an array of objects (removing the external curly braces) like

var text = '[{ "id": 999, "username": "Batman" } ]';

objs = JSON.parse(text);
var id = objs[0].id;
console.log(id); // 999

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745240458a4618150.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信