我有一个字符串as

string = "firstName:name1, lastName:last1"; 

现在我需要一个对象obj这样

obj = {firstName:name1, lastName:last1}

我如何在JS中做到这一点?


当前回答

你需要使用JSON.parse()将String转换为Object:

var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');

其他回答

string = "firstName:name1, lastName:last1";

这是可行的:

var fields = string.split(', '),
    fieldObject = {};

if( typeof fields === 'object') ){
   fields.each(function(field) {
      var c = property.split(':');
      fieldObject[c[0]] = c[1];
   });
}

然而,这并不是有效的。当你有这样的东西时会发生什么:

string = "firstName:name1, lastName:last1, profileUrl:http://localhost/site/profile/1";

Split()将拆分'http'。所以我建议您使用一个特殊的分隔符,如pipe

 string = "firstName|name1, lastName|last1";


   var fields = string.split(', '),
        fieldObject = {};

    if( typeof fields === 'object') ){
       fields.each(function(field) {
          var c = property.split('|');
          fieldObject[c[0]] = c[1];
       });
    }

由于JSON.parse()方法需要将对象键括在引号中才能正确工作,因此在调用JSON.parse()方法之前,我们首先必须将字符串转换为JSON格式的字符串。

var obj = '{firstName:"John", lastName:"Doe"}'; var jsonStr = obj.replace(/(\w+:)|(\w+:)/g,函数(匹配str) { 返回' ' ' + matchedStr。substring (0, matchedStr。长度- 1)+ '":'; }); obj = JSON.parse(jsonStr);//转换为常规对象 console.log (obj.firstName);//期望输出:John console.log (obj.lastName);//期望输出:Doe

即使字符串有一个复杂的对象(如下所示),这也可以工作,并且仍然可以正确地转换。只要确保字符串本身是用单引号括起来的。

var strorobj = '{名字:"John Doe",年龄:33岁,最爱:{体育:["篮球","棒球"],电影:["星球大战","出租车司机"]}}'; var jsonStr = strObj.replace (/ (\ w +:) | (\ w +:) / g函数(s) { 返回' ' ' + s.substring(0, s.length-1) + ' ' ':'; }); var obj = JSON.parse(jsonStr); console.log (obj.favorites.movies [0]);//期望输出:Star Wars . //

在你的情况下

var KeyVal = string.split(", ");
var obj = {};
var i;
for (i in KeyVal) {
    KeyVal[i] = KeyVal[i].split(":");
    obj[eval(KeyVal[i][0])] = eval(KeyVal[i][1]);
}
const text = '{"name":"John", "age":30, "city":"New York"}';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr.name;
var stringExample = "firstName:name1, lastName:last1 | firstName:name2, lastName:last2";    

var initial_arr_objects = stringExample.split("|");
    var objects =[];
    initial_arr_objects.map((e) => {
          var string = e;
          var fields = string.split(','),fieldObject = {};
        if( typeof fields === 'object') {
           fields.forEach(function(field) {
              var c = field.split(':');
              fieldObject[c[0]] = c[1]; //use parseInt if integer wanted
           });
        }
            console.log(fieldObject)
            objects.push(fieldObject);
        });

"objects"数组将包含所有对象