gpt4 book ai didi

javascript - 将 JSON 对象转换为嵌套表单字段?

转载 作者:行者123 更新时间:2023-11-29 18:37:54 25 4
gpt4 key购买 nike

任何人都知道将 JSON 对象转换为嵌套表单字段的好方法。

例如:考虑一个 JSON 对象:

{'a':{'b':{'c':'1200'}}}, 'z':'foo', 'bar':{'baz':'1', 'id':2}}

我应该得到:

{'a[b][c]':'1200', 'z':'foo', 'bar[baz]':'1', 'bar[id]':2};

有什么想法吗?

我目前正在使用 jquery,感觉像这样的东西已经存在了,如果没有,我可以简单地用一个疯狂的算法来推出我自己的东西,但我宁愿使用有良好记录的东西。

最佳答案

所以,我不知道你为什么要按照你说的去做,我希望你能把我们都填进去,但这段代码应该足够接近,以便你能够调整它(这是基于 some code of mine that I use to find differences in JavaScript object graphs ):

function doStrangeThing(obj) {
var propertyChanges = [];
var objectGraphPath = [];
(function(obj, refObj) {
if ( obj.constructor == Object || (obj.constructor != Number &&
obj.constructor != String && obj.constructor != Date && obj.constructor != Boolean &&
obj.constructor != RegExp && obj.constructor != Function)) {
for (var property in obj) {
objectGraphPath.push((objectGraphPath.length > 0) ? "[" + property + "]" : property);
if (obj[property].constructor != Function) {
if (!refObj[property]) refObj[property] = {};
arguments.callee(obj[property], refObj[property]);
}
objectGraphPath.pop();
}
} else if (obj.constructor != Function) {
if (obj != refObj) {
propertyChanges.push("\"" + objectGraphPath.join("") + "\":\"" + obj.toString() + "\"");
}
}
})(obj, {});
return "{" + propertyChanges.join(",") + "}";
}

下面是我做的测试:

doStrangeThing({'a':{'b':{'c':'1200'}}, 'z':'foo', 'bar':{'baz':'1', 'id':2}});

产生这个值:

{"a[b][c]":"1200","z":"foo","bar[baz]":"1","bar[id]":"2"}

希望这在某种程度上对你有用......

关于javascript - 将 JSON 对象转换为嵌套表单字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/813370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com