使用jquery each()从object获取特定值

时间:2016-05-19 12:14:39

标签: jquery

[Object, Object]
0:Object
 chat:"i like to say hello"
 id:13
 user_id:1
 yiinput_id:5
 __proto__:Object
1:Object
 chat:"another chat here"
 id:14
 user_id:1
 yiinput_id:5
 __proto__:Object
length:2
__proto__:Array[0]

我正在尝试使用表格中的一些信息填充列表。我有上述目标,我想要获得这样的值:

$.each(resp.chats, function() {
            $.each(this, function(k, v) {
                console.log(k + ' ' + v);//this gets me all keys and values but i need specific key value
            console.log("Chat ="+ //need chat value here );
            console.log("User ID ="+ //need id value here );
            });
        });

2 个答案:

答案 0 :(得分:2)

您可以直接访问chats数组中对象的属性,而无需其他循环。试试这个:

$.each(resp.chats, function(i, chat) {
    var value = chat.chat;
    var userId = chat.user_id;

    // use the variables as required here...
    console.log(value, userId);
});

答案 1 :(得分:2)

你可以通过结构来获得它。

$.each(resp.chats, function(index, element) {
    console.log("Chat ="+ element.chat );
    console.log("User ID ="+ element.user_id );
});