Firdaus
Firdaus

Reputation: 43

Converting an object to multiple arrays

I have a JSON file "icon.json" which contains:

[
    {
        "name": "sad",
        "url": "1.gif"
    },
    {
        "name": "smile",
        "url": "2.gif"
    },
    {
        "name": "smile2",
        "url": "3.gif"
    }
]

And I load it with AJAX in my html file

var c1 = [];
var c2 = [];
function testget(){
    $.ajax({
        url: 'icon.json',
        type: 'GET'
    })
    .done(function(msg) {
        // how to convert msg to array c1 and c2
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });
}
$(document).ready(function() {
    testget();
});

Please tell me how to convert the object returned from the AJAX call to array c1 and c2 like this:

c1 = ["sad", "smile", "smile2"];
c2 = ["1.gif", "2.gif", "3.gif"];

Upvotes: 2

Views: 56

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can do this with a simple loop:

.done(function(msg) {
    for (var i = 0; i < msg.length; i++) {
        c1.push(msg[i].name);
        c2.push(msg[i].url);
    }
})

Example fiddle

Upvotes: 8

Related Questions