0

I've the following string in the JavaScript:

test: hi,
otherTest: hiAgain

How can I transform in a key: value array?

2
  • 2
    looking for split Commented Jul 2, 2015 at 17:21
  • But how to do? I'm already using split to separate the string on the commas but I don't know how to do separate in a key: value array. Commented Jul 2, 2015 at 17:25

3 Answers 3

2
var string = 'test: hi,otherTest: hiAgain';
var sets = string.split(","); //splits string by commas
var out = new Array(); //prepare the output array
for (var i=0; i<sets.length; i++) {
  var keyval = sets[i].split(":"); //split by colon for key/val
  out[keyval[0]] = keyval[1].trim(); //trim off white spaces and set array
}
Sign up to request clarification or add additional context in comments.

5 Comments

an Array is not required here, as keys will be string (adding propertie to the object) and not indexes. And the length will not be updated as you don't push to the array
@Hacketo except the question specifically asks for an array. Also the length should not update. It is taking the original string and breaking it up to create the new array. Push is not required if you know the key you are setting it to.
OP is asking for a 'key:value array', and that does not exist in javascript, it's a raw object.
@Hacketo ah i misunderstood. I thought he meant key:value as in the format of how he wanted the array broken up.
You code is right, it's just the type of 'out', a raw object would do the same, without any misunderstand about arrays.
1

Here is a quick example:

var str='test: hi,\notherTest: hiAgain';

var obj={};
var kvp=str.split('\n');
for(k=0;k<kvp.length;k++){
  var temp=kvp[k].split(' ');
  obj[temp[0]]=temp[1];
}
console.log(JSON.stringify(obj));

Comments

1

Here you are:

var data = ['test: hi', 'otherTest: hiAgain'];
var result = [];
$.each(data, function(index, value){
    var keyValue = value.split(':');
    var obj = {};
    obj[keyValue[0].trim()] = keyValue[1].trim();
    result.push(obj);
});
alert(JSON.stringify(result));

Hope this help.

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.