开发者

Create JavaScript object of asterisk separated strings

开发者 https://www.devze.com 2023-01-04 05:05 出处:网络
I\'ve three strings. var 开发者_如何学Goids = \"1*2*3\"; var Name =\"John*Brain*Andy\"; var Code =\"A12*B32*C38\";

I've three strings.

var 开发者_如何学Goids = "1*2*3";
var Name ="John*Brain*Andy";
var Code ="A12*B32*C38";

I want to create a JavaScript object of it.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消