IsmailS
IsmailS

Reputation: 10863

Create JavaScript object of asterisk separated strings

I've three strings.

var ids = "1*2*3";
var Name ="John*Brain*Andy";
var Code ="A12*B32*C38";

I want to create a JavaScript object of it.

Upvotes: 0

Views: 1063

Answers (2)

Oleg
Oleg

Reputation: 221997

I find that Guffa give a good answer. I want only dissuade from the manual JSON serialisation because Name properties could have a special characters which must be escaped. So I suggest a minimal change of Guffa's suggestion and use JSON.stringify (see http://www.json.org/js.html)

var Ids = ids.split('*'), names = Name.split('*'), codes = Code.split('*');
var arr = [];
for (var i = 0; i < Ids.length; i++) {
  arr.push({ Id: Ids[i], Name: names[i], Code: codes[i] });
}
var result = JSON.stringify(arr);

Upvotes: 1

Guffa
Guffa

Reputation: 700362

A JSON object is just a string, so it would be:

var json = '{"ids":"'+ids+'","Name":"'+Name+'","Code":"'+Code+'"}';

If you want the strings converted into string arrays:

var json = '{"ids":["'+ids.replace(/\*/g,'","')+'"],"Name":["'+Name.replace(/\*/g,'","')+'"],"Code":["'+Code.replace(/\*/g,'","')+'"]}';

If you are not at all looing for JSON, but in fact a Javascript object, it would be:

var obj = {
  ids: ids.split('*'),
  Name: Name.split('*'),
  Code: Code.split('*')
};

Based on your description "I want first item of the array to be having three props i.e. Id, name and code with values 1,John, A12 respectively." it would however be completely different:

var Ids = ids.split('*'), names = Name.split('*'), codes = Code.split('*');
var arr = [];
for (var i = 0; i < Ids.length; i++) {
  arr.push({ Id: Ids[i], name: names[i], code: codes[i] });
}

And if you want that as JSON, it would be:

var Ids = ids.split('*'), names = Name.split('*'), codes = Code.split('*');
var items = [];
for (var i = 0; i < Ids.length; i++) {
  items.push('{"Id":"'+Ids[i]+'","name":"'+names[i]+'","code":"'+codes[i]+'"}');
}
json = '[' + items.join(',') + ']';

(Note: The last code only works properly when the strings doesn't contain any quotation marks, otherwise they have to be escaped when put in the string.)

Upvotes: 2

Related Questions