如何访问JSON对象数组的第一个元素?

Hed*_*dge 16 javascript arrays json

我知道mandrill_events只包含一个对象.我如何访问它event-property

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }
Run Code Online (Sandbox Code Playgroud)

Anu*_*uga 18

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }

console.log(Object.keys(req)[0]);
Run Code Online (Sandbox Code Playgroud)

创建任何Object数组(req),然后只需Object.keys(req)[0]选择Object数组中的第一个键.


sto*_*roz 13

要回答您的名义问题,您可以使用[0]访问第一个元素,但因为它mandrill_events包含的字符串不是数组,所以mandrill_events[0]只能获得第一个字符'['.

因此,要么将您的来源更正为:

var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
Run Code Online (Sandbox Code Playgroud)

然后req.mandrill_events[0],或者如果你坚持使用它是一个字符串,解析字符串包含的JSON:

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];
Run Code Online (Sandbox Code Playgroud)

  • 感谢您指出,如果变量是字符串而不是对象,则“[”将作为内容返回 (2认同)

Tos*_*ade 7

我将用一个一般的例子来解释这一点:

var obj = { name: "John", age: 30, city: "New York" };
var result = obj[Object.keys(obj)[0]];
Run Code Online (Sandbox Code Playgroud)

结果变量的值为“John”


sem*_*gay 6

事件属性似乎首先是字符串,您必须将其解析为 json :

 var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
 var event = JSON.parse(req.mandrill_events);
 var ts =  event[0].ts
Run Code Online (Sandbox Code Playgroud)