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

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

programmeradmin2浏览0评论
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
发布评论

评论列表(0)

  1. 暂无评论