0

I am using Jquery ajax and i get XML back something like

<tabs>
<tab>
<id>1</id>
<name>firstname</name>
<lastname>surname1</lastname>
</tab>

<tab>
<id>2</id>
<name>secondname</name>
<lastname>surname2</lastname>
</tab>
</tabs>

In jquery i would like to store it in object something like below

var obj = {
    '1' : {
        'name' : 'firstname',
        'lastname' : 'surname1'
    },
    '2' : {
        'name' : 'secondname',
        'lastname' : 'surname2'
    }
};

so that based on key i can directly access its value.

  obj.2.name should return me second name

Any jQuery expert please help me.

Below is my Jquery code which i am trying to update but not getting any clue how to make it work.

Thank you in advance.

$.ajax({
            url: __BASEURL + "portal/getusertabs.php",
            data: {user_id: user_id},
            type: "POST",
            dataType: 'XML',
            cache: false,
            async: false,
            success: function(data, textStatus, jqXHR) {
                $(data).find('tabs').each(function() {
                    $(this).find('tab').each(function() { 
                        var tab_id = $(this).find('id').text();
                        var tab_name = $(this).find('name').text();
                        var tab_lastname = $(this).find('last name').text();
                        tab.push({id : tab_id, name : tab_name, lastname : tab_lastname});
                    });
                });
            }
        });
2
  • jsfiddle.net/xnPF3 Commented May 24, 2014 at 14:43
  • Do something like Deserialize xml to object. Also take a look at this Commented May 24, 2014 at 14:44

1 Answer 1

0

Note that you do not need to loop over tabs because that is the root element and there should only be 1 of them. You also need to set the id of the tab as the key of the object. Try this:

$(data).find('tab').each(function () {
    var tab_id = $(this).find('id').text();
    var tab_name = $(this).find('name').text();
    var tab_lastname = $(this).find('lastname').text();
    tab[tab_id] = {
        name: tab_name,
        lastname: tab_lastname
    };
});

console.log(tab);

Example fiddle

Note that using tab.2.name is not valid javascript as numerical values cannot be used as identifiers. Instead you will need to use this:

tab['2'].name // = 'secondname'
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Roy.. thank you so much for your help. Is it possible to ready all the items from tab objects in loop?
That's what this is doing. It will get the values from all tab elements and put them in the object.
Sorry Rory.. i meant is it possible to loop tab{} somewhere else to display its contents...
Ah, yes you can use for each (var item in tab) { /* code here */ }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.