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});
                    });
                });
            }
        });
SmartDev
  • 481
  • 3
  • 11
  • 30
  • http://jsfiddle.net/xnPF3/ – adeneo May 24 '14 at 14:43
  • Do something like Deserialize xml to object. Also take a look at **[this](http://stackoverflow.com/questions/10114591/deserialize-xml-to-object-with-symfony2)** – super May 24 '14 at 14:44

1 Answers1

1

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'
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339