-3

I have a string like this

var information = 'name:ozil,age:22,gender:male,location:123 street';

I want to make an array of key value object like this

var informationList=[
    {
       'key':'name',
       'value':'ozil'
    },
    {
       'key':'gender',
       'value':'male'
    },
    {
       'key':'location',
       'value':'123 street'
    },

]
ozil
  • 6,930
  • 9
  • 33
  • 56

3 Answers3

4

Using split and map:

var information = 'name:ozil,age:22,gender:male,location:123 street',
    result = information.split(',').map(function(item){
      var arr = item.split(':');
      
      return {
        key: arr[0],
        value: arr[1]
      }
    });


document.write(JSON.stringify(result));
CD..
  • 72,281
  • 25
  • 154
  • 163
1

You can try this:

var list = [];
var pairs = information.split(',');
for (var i = 0; i < pairs.length; i++) {
    var p = pairs[i].split(':');
    list.push({
        key: p[0],
        value: p[1]
    });
}
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
0

This should do it:

var input = "name:ozil,age:22,gender:male,location:123 street";
var temp = input.split(",");
var result = [];
for(var i=0; i < temp.length; i++) {
    var temp2 = temp[i].split(":");
    result.push({key:temp2[0], value:temp2[1]});
}
console.log(result);

result now contains what you specified.

JPS
  • 411
  • 6
  • 16