创建以星号分隔的字符串的JavaScript对象 [英] Create JavaScript object of asterisk separated strings

查看:137
本文介绍了创建以星号分隔的字符串的JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个琴弦.

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

我想为其创建一个JavaScript对象.

I want to create a JavaScript object of it.

推荐答案

JSON对象只是一个字符串,因此它将是:

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,'","')+'"]}';

如果您根本不希望使用JSON,而是实际上是Javascript对象,那么它将是:

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('*')
};

根据您的描述我希望数组的第一项具有三个属性,即ID,名称和代码分别具有值1,John,A12."但是,它将完全不同:

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] });
}

如果您希望将其作为JSON,则为:

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

这篇关于创建以星号分隔的字符串的JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆