我有一个字符串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中做到这一点?
当前回答
const text = '{"name":"John", "age":30, "city":"New York"}';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr.name;
其他回答
const text = '{"name":"John", "age":30, "city":"New York"}';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr.name;
你的字符串看起来像一个没有花括号的JSON字符串。
这应该工作,然后:
obj = eval('({' + str + '})');
警告:这会引入重大的安全漏洞,例如使用不受信任的数据(应用程序用户输入的数据)进行XSS。
下面是我处理一些边缘情况的方法,比如将空格和其他基本类型作为值
const str = " c:234 , d:sdfg ,e: true, f:null, g: undefined, h:name ";
const strToObj = str
.trim()
.split(",")
.reduce((acc, item) => {
const [key, val = ""] = item.trim().split(":");
let newVal = val.trim();
if (newVal == "null") {
newVal = null;
} else if (newVal == "undefined") {
newVal = void 0;
} else if (!Number.isNaN(Number(newVal))) {
newVal = Number(newVal);
}else if (newVal == "true" || newVal == "false") {
newVal = Boolean(newVal);
}
return { ...acc, [key.trim()]: newVal };
}, {});
在你的情况下
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 properties = string.split(', ');
var obj = {};
properties.forEach(function(property) {
var tup = property.split(':');
obj[tup[0]] = tup[1];
});
我假设属性名在冒号的左边,它所取的字符串值在右边。
注意Array。forEach是JavaScript 1.6——您可能需要使用工具包来实现最大的兼容性。