views:

40

answers:

2

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.

+2  A: 

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

Guffa
I think the OP confuses JSON strings with JavaScript objects.
Marcel Korpel
@Marcel: Perhaps. I add some Javacript code also...
Guffa
ID 1 is for John and A12 is his code. So I want first item of the array to be having three props i.e. Id, name and code with values 1,John, A12 respectively. And yes I was looking for Javascript object. But I confused it with JSON
Ismail
Thank you very much. Can you please also answer this one http://stackoverflow.com/questions/3075343/group-javascript-items-by-one-property
Ismail
How should I access Id property on first item? I'm trying to access value 1 on `arr[0].Id` but I'm getting empty string
Ismail
Its working. I'm sorry! My string starts with asterisk so first item is empty.
Ismail
+1  A: 

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);
Oleg
+1 Thank you Oleg. Currently I don't need JSON of it. I will edit the question. I will use stringify when I will need JSON. Thanks again
Ismail