Aldi Unanto
Aldi Unanto

Reputation: 3682

JS - Set multidimensional array from AJAX output

Let's say I receive some data from jQuery Ajax output.

var tags = call_ajax('order/get_data', 'user_id=' + $('#user_id').val());

Outputted string from PHP file something like this :

echo "Aldi:01|Andi:02|Martin:03";

So my question is, how to .split() that outputted string(tags) become JS array with format like :

var source: [
                {'value' : 'Aldi', 'id' : '01'},
                {'value' : 'Andi', 'id' : '02'},
                {'value' : 'Martin', 'id' : '03'}
            ]

Thanks in advance!

Upvotes: 0

Views: 112

Answers (4)

Lochemage
Lochemage

Reputation: 3974

First split the string by the bar character .split('|') to get an array of three items, then loop through each of those items and split them again for the value/id pairs and put it into your final array.

var responseEcho; // assume this is your response from the server.
var myArray = responseEcho.split('|');
var finalArray = [];
myArray.forEach(function(data) {
  var dataArray = data.split(':');
  finalArray.push({'value': dataArray[0], 'id': dataArray[1]});
});

You may want to include a bit more safety checking just in case, but that is the general idea.

Upvotes: 0

Jeffrey Neo
Jeffrey Neo

Reputation: 3809

var output = 'Aldi:01|Andi:02|Martin:03';
var data = output.split('|');
var source = new Array();

for(var key in data){
    var temp = data[key].split(':');
    source[key] = {'value':temp[0],'id':temp[1]};
}

By using,

for(var key in source){
    alert(source[key]['value']);
    alert(source[key]['id']);
}

Upvotes: 1

Bergi
Bergi

Reputation: 664650

With the Array map method:

var source = tags.split("|") // first split by `|`
  .map(function(tag) {
    // then construct the object for each part
    var parts = tag.split(":");
    return { value: parts[0], id: parts[1] };
  });

Upvotes: 2

Bill Criswell
Bill Criswell

Reputation: 32921

You can do it with two splits pretty easily.

var s = 'Aldi:01|Andi:02|Martin:03', 
    parts = s.split('|'), 
    source = [];

for( var i = 0, l = parts.length; i < l; i++ ){
  var part = parts[i].split(':');
  source.push({ value: part[0], id: part[1] });
}

Upvotes: 1

Related Questions