我有一个如下的 JSON 字符串:{firstname: "foo", lastname: "bar", message: "I'm fubar" }
并希望将每个值分配给一个与其相应键完全相同的变量:
我应该得到一个var firstname
或对象obj.firstname
来分配值“foo”,等等......
项目列表显然应该扩展,所以我不想硬编码键/变量名称来分配每个值。
完成这个非常简单的任务的好方法是什么?
是否存在一种 getElementById 类型的解决方案来为 key 标识的变量分配其各自的值?
这就是我正在尝试的,带有一些伪代码:
var firstname = "";
var lastname = "";
// etc...
var data = JSON.parse({firstname: "foo", lastname: "bar", message: "I'm fubar", age: "etc..."});
for (var key in data) {
("the variable currently identified by the value of key").val(data[key]);
// or any other way of assigning "foo" to firstname
console.log("firstname: " + firstname + ", lastname: " + lastname);
}
然后打印
firstname: foo, lastname: bar