Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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'
    },

]
share|improve this question
2  
And what have tried so far? SO is not a code-request community. –  Yoshi Nov 25 '14 at 11:46
    
google javascript split function –  bigbobr Nov 25 '14 at 11:46
    
Naive approach: 'name:ozil,age:22,gender:male,location:123 street'.split(',').map(function(el) { var p = el.split(':'); return {key: p[0], value: p[1]}; }) –  dfsq Nov 25 '14 at 11:49
    

3 Answers 3

up vote 1 down vote accepted

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]
    });
}
share|improve this answer

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));

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.