Ciprian
Ciprian

Reputation: 3226

Get specific value from object using jquery each()

[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]

I am trying to populate a list with some information from a table. I have the above object and I am tying to get values like this:

$.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 );
            });
        });

Upvotes: 1

Views: 2023

Answers (2)

hurricane
hurricane

Reputation: 6724

You can get it with structure.

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

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can access the properties of the object within the chats array directly without needing another loop. Try this:

$.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);
});

Upvotes: 2

Related Questions