1

我有一个由 PHP 发送到 Javascript 的动态生成的数组。它基本上是一组未读消息。它包含发件人的姓名和他们发送的消息。

鉴于我不知道名字,我如何检索他们的名字和他们的消息?

{"Emma Giles":
[{"message":"Hi Phil","date":"Tue 10 May 2:55 PM 2011"}],
"Johnathan Macmanners":
[{"message":"Hi Emma","date":"Sun 26 June 10:03 PM 2011"}],
"Ellen Murley":
[{"message":"Hello","date":"Fri 04 May 4:05 PM 2012"},
{"message":"How are you?","date":"Fri 04 May 2:52 PM 2012"}],
"Amanda Patterson":
[{"message":"test","date":"Fri 27 April 10:07 AM 2012"}],
"ALEX Pell":
[{"message":"Hi Alvon","date":"Mon 05 March 10:07 AM 2012"}]}

我已经尝试过了,但由于某种原因它只打印出数字,我用 val 替换了 key ,它一个一个地打印出数组中的每个字符。:

$.each(data, function(key, val)
{
    console.log(key);
});
4

4 回答 4

1

您的父容器是一个对象,而不是一个数组。然后你有一个嵌套的对象数组。

for (var key in data) {
    // key is the name of the person,
    // data[key] is the array containing the message data

    for (var i = 0, l = data[key].length; i < l; i++) {
      for (var msgKey in data[key][i]) {
         // msgKey will be "message" or "date"
         // data[key][i][msgKey] is the value of each key
      }  
    }
}
于 2012-05-09T17:25:54.807 回答
1

稍微清理一下你的 JSON,你有一个由指向消息对象数组的用户名组成的哈希:

var data = {
  "Emma Giles": [
    {"message":"Hi Phil","date":"Tue 10 May 2:55 PM 2011"}
  ],
  "Johnathan Macmanners": [
    {"message":"Hi Emma","date":"Sun 26 June 10:03 PM 2011"}
  ]
};

你几乎可以得到你想要的:

$.each(data, function(name, messages) {
   var messageText = messages[0].message;

   alert(name + ': ' + messageText);
});

仅供参考,这里有一个小提琴

于 2012-05-09T17:28:52.243 回答
0

看起来您的数据仍被序列化并被识别为字符串。

尝试使用以下方式获取您的数据:

$.getJSON(url, function (data) {
    $(data).each(function (key, value) {
        // ...
    });
});

...或使用一个好的 ol' eval(),但如果可以的话,你宁愿避免它。

于 2012-05-09T17:28:48.793 回答
0

这也将起作用:

var a = {"Emma Giles":
[{"message":"Hi Phil","date":"Tue 10 May 2:55 PM 2011"}],
"Johnathan Macmanners":
[{"message":"Hi Emma","date":"Sun 26 June 10:03 PM 2011"}],
"Ellen Murley":
[{"message":"Hello","date":"Fri 04 May 4:05 PM 2012"},
{"message":"How are you?","date":"Fri 04 May 2:52 PM 2012"}],
"Amanda Patterson":
[{"message":"test","date":"Fri 27 April 10:07 AM 2012"}],
"ALEX Pell":
[{"message":"Hi Alvon","date":"Mon 05 March 10:07 AM 2012"}]};

var keys = Object.keys(a);
for(var i = 0, max = keys.length; i < max; i++){
    var key = keys[i]; //name
    var val = a[key]; //messages array
    console.log(key);
    for(var j = 0, jmax = val.length; j < jmax; j++){
        var message = val[j].message;
        console.log("      "+message);
    }

}
于 2012-05-09T17:34:14.133 回答