我有一个字符串as
string = "firstName:name1, lastName:last1";
现在我需要一个对象obj这样
obj = {firstName:name1, lastName:last1}
我如何在JS中做到这一点?
我有一个字符串as
string = "firstName:name1, lastName:last1";
现在我需要一个对象obj这样
obj = {firstName:name1, lastName:last1}
我如何在JS中做到这一点?
当前回答
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"数组将包含所有对象
其他回答
在你的情况下
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]);
}
这个简单的方法…
var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);
alert(obj.firstName);
输出
name1
这是通用代码,不管你的输入有多长,但如果有:分隔符:)
var string = "firstName:name1, lastName:last1";
var pass = string.replace(',',':');
var arr = pass.split(':');
var empty = {};
arr.forEach(function(el,i){
var b = i + 1, c = b/2, e = c.toString();
if(e.indexOf('.') != -1 ) {
empty[el] = arr[i+1];
}
});
console.log(empty)
const text = '{"name":"John", "age":30, "city":"New York"}';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr.name;
如果我没理解错的话:
var properties = string.split(', ');
var obj = {};
properties.forEach(function(property) {
var tup = property.split(':');
obj[tup[0]] = tup[1];
});
我假设属性名在冒号的左边,它所取的字符串值在右边。
注意Array。forEach是JavaScript 1.6——您可能需要使用工具包来实现最大的兼容性。