如何从嵌套的json对象中提取值并将它们连接起来?

时间:2013-12-19 05:59:17

标签: javascript jquery json

我有一个以下格式的javascript对象。我想将每个块的名称和状态组合在一起并存储在一个数组中。

{
    "datatype": "local",
    "data": [
        {
            "Name": "John",
            "status": "To Be Processed",
            "LastUpdatedDate": "2013-05-31 08:40:55.0"
        },
        {
            "Name": "Paul",
            "status": "To Be Processed",
            "LastUpdatedDate": "2013-06-02 16:03:00.0"
        }

}

所需输出

John + To Be Processed
Paul + To Be Processed

请帮助?

2 个答案:

答案 0 :(得分:1)

您可以使用$.map()创建已处理值列表

var data = {
    "datatype": "local",
    "data": [{
        "Name": "John",
        "status": "To Be Processed",
        "LastUpdatedDate": "2013-05-31 08:40:55.0"
    }, {
        "Name": "Paul",
        "status": "To Be Processed",
        "LastUpdatedDate": "2013-06-02 16:03:00.0"
    }]
};

var result = $.map(data.data, function(obj){
    return obj.Name + ' ' + obj.status
});

console.log(result)

答案 1 :(得分:1)

注意:您的json无效。它应该是

"data": [{...},{...}] // ] is mising

var data = {
    "datatype": "local",
    "data": [
        {
            "Name": "John",
            "status": "To Be Processed",
            "LastUpdatedDate": "2013-05-31 08:40:55.0"
        },
        {
            "Name": "Paul",
            "status": "To Be Processed",
            "LastUpdatedDate": "2013-06-02 16:03:00.0"
        }]
};
var len = data.data.length;
var txt = "";
for(var i=0;i<len;i++){
    txt += "<div>"+data.data[i].Name+" "+data.data[i].status+"</div>";
}
$("body").append(txt);

DEMO here.