0
aaa 3333,bbb 5,ccc 10

First i need to split based on Comma and the i need to split based on space to make it key value pair... how do i do in JavaScript.

7 Answers 7

5
var pairs = {};
var values = "aaa 3333,bbb 5,ccc 10".split(/,/);

for(var i=0; i<values.length; i++) {
  var pair = values[i].split(/ /);
  pairs[pair[0]] = pair[1];
}

JSON.stringify(pairs) ; //# => {"aaa":"3333","bbb":"5","ccc":"10"}
Sign up to request clarification or add additional context in comments.

Comments

3

Use the split method:

var items = str.split(',');
for (var i = 0; i < items.length; i++) {
  var keyvalue = items[i].split(' ');
  var key = keyvalue[0];
  var value = keyvalue[1];
  // do something with each pair...
}

1 Comment

Wow, posted at exactly the same second as me :)
3

What about something like this :

var str, arr1, arr2, i;
str = 'aaa 3333,bbb 5,ccc 10';
arr1 = str.split(/,/);
for (i=0 ; i<arr1.length ; i++) {
    arr2 = arr1[i].split(/ /);
    // The key is arr2[0]
    // the corresponding value is arr2[1]
    console.log(arr2[0] + ' => ' + arr2[1]);
}

Comments

2

Code says more than a thousand words.

var str = "aaa 3333,bbb 5,ccc 10";
var spl = str.split(",");
var obj = {};
for(var i=0;i<spl.length;i++) {
    var spl2 = spl[i].split(" ");
    obj[spl2[0]] = spl2[1];
}

Comments

2
var s = 'aaa 3333,bbb 5,ccc 10';
var tokens = s.split(',');
var kvps = [];
if (tokens != null && tokens.length > 0) {
    for (var i = 0; i < tokens.length; i++) {
        var kvp = tokens[i].split(' ');
        if (kvp != null && kvp.length > 1) {
            kvps.push({ key: kvp[0], value: kvp[1] });
        }
    }
}

Comments

2

Use String.split() : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

var theString = 'aaa 3333,bbb 5,ccc 10';
var parts = theString.split(',');
for (var i=0; i < parts .length; i++) {
    var unit = parts.split(' ');
    var key = unit[0];
    var value = unit[1];
}

Comments

0

// this thread needs some variety...

function resplit(s){
    var m, obj= {},
    rx=/([^ ,]+) +([^,]+)/g;
    while((m= rx.exec(s))!= null){
        obj[m[1]]= m[2];
    };
    return obj;
}

var s1= 'aaa 3333,bbb 5,ccc 10';
var obj1=resplit(s1);


/*  returned value: (Object)
{
    aaa: '3333',
    bbb: '5',
    ccc: '10'
}

*/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.