我已遍历document.form.element,将名称构造成数组名称,如下所示:
它们的一些名称在JSON中是这样的:
{
data[name]: "foo",
data[address]: "baz drive",
data[city]: "Dallas",
data[state]: "Texas",
data[phone]: "555-1212"
}
有没有办法在不使用eval
的情况下使用Pure JavaScript(没有像jQuery这样的框架)将其转换为此?:
{
data: {
name: "foo",
address: "baz drive",
city: "Dallas",
state: "Texas",
phone: "555-1212"
}
}
<script type="javascript">
var o = {
data[name]: "foo",
data[address]: "baz drive",
data[city]: "Dallas",
data[state]: "Texas",
data[phone]: "555-1212"
}
var temp = [];
for (key in o) {
temp[JSON.parse(key)] = o;
}
</script>
小提琴在这里:http://jsfiddle.net/chrisjlee/medbzv9a/
或者这不是完全可能的吗?
答案 0 :(得分:2)
喜欢
var o = {
"data[name]": "foo",
"data[address]": "baz drive",
"data[city]": "Dallas",
"data[state]": "Texas",
"data[phone]": "555-1212"
};
o.data = {};
for (key in o) {
var index = key.match(/[^[\]]+(?=])/g);
if(index) {
o.data[index] = o[key];
delete(o[key]);
}
}
console.log(o);
答案 1 :(得分:1)
以下函数应修复该对象。它将以递归方式执行,也可以处理数组。
var fixKeys = function(obj) {
if (typeof(obj) != "object")
return obj;
if (Object.prototype.toString.call(obj) == "[object Array]")
return obj.map(arguments.callee);
var newObj = {};
for (var key in obj) {
if (!obj.hasOwnProperty(key))
continue;
var m = /^(\w+)\[(\w+)\]$/.exec(key);
if (m) {
newObj[m[1]] = newObj[m[1]] || {};
newObj[m[1]][m[2]] = arguments.callee(obj[key]);
} else {
newObj[key] = arguments.callee(obj[key]);
}
}
return newObj;
};
这是一个更好的版本,它可以处理这种类型的数据:
var o = {
"data[name]": "foo",
"data[address][street]": "baz drive",
"data[address][city]": "Dallas",
"data[address][state]": "Texas",
"data[phone]": "555-1212",
someArray: [
{"test[a]": 42},
42
]
};
万一你需要它:
var fixKeys = function(obj) {
if (typeof(obj) != "object")
return obj;
if (Object.prototype.toString.call(obj) == "[object Array]")
return obj.map(arguments.callee);
var newObj = {};
for (var key in obj) {
if (!obj.hasOwnProperty(key))
continue;
var m = /^(\w+)(?:\[\w+\])+$/.exec(key);
if (m) {
var subKey = key.substr(m[1].length);
var subObj = newObj[m[1]] = newObj[m[1]] || {};
while (m = /^\[(\w+)\]\[/.exec(subKey)) {
subObj = subObj[m[1]] = subObj[m[1]] || {};
subKey = subKey.substr(m[0].length - 1);
}
m = /^\[(\w+)\]$/.exec(subKey);
subObj[m[1]] = arguments.callee(obj[key]);
} else {
newObj[key] = arguments.callee(obj[key]);
}
}
return newObj;
};