gpt4 book ai didi

javascript - 在 Javascript 中构建复杂的 JSON

转载 作者:行者123 更新时间:2023-12-01 04:00:27 25 4
gpt4 key购买 nike

刚刚开始使用 JavaScript,需要一些关于如何最好地动态/动态创建/构建下面的 JSON 的指导。

一些键需要来自变量。例如,在下面的 JSON 中,名为“variable_key_*”的键需要来自变量。

{
"static_key_1": "value",
"static_key_2": [{
"static_key_3": {
"id": "1097274153"
},
"static_key_4": "value",
"static_key_5": {
"static_key_6": {
"variable_key_1": "value",
"variable_key_2": "value",
"variable_key_3": "value"
},
"static_key_7": {
"static_key_8": [
"value"
]
}
}
}]
}

最佳答案

您可以使用括号表示法在带有变量的对象中设置键。

let theVariable = 'useful_name';
let theValue = 12345;
let myObj = {};

myObj [ theVariable ] = theValue;

将导致:

{ useful_name : 12345 }

并按照您的预期进行字符串化。

根据更多信息的请求进行编辑:

假设您想创建一个包含对象数组的嵌套对象,我们将使用已有的对象。

myObj [ someOtherVar ] = {};
let myObjSomeOtherVar = myObj [ someOtherVar ];
myObjSomeOtherVar [ someOtherKey ] = [ ].push ( { } );
let theArrayOfObjects = myObjSomeOtherVar [ someOtherKey ];
theArrayOfObjects [ 0 ] [ anotherKeyName ] = 'hello';

这会导致(假设您实际上声明了所有变量等)

{ useful_name : 12345,
valOfSomeOtherVar :
{ valOfSomeOtherKey :
[ { valOfAnotherKeyName : 'hello' } ]
}
}

诀窍是抽象地开发您的数据模式(因此您想要的骨架),然后编写一个构建它的例程。我很少以这种方式手动构建一个对象,除非它只是一个小的 util obj,我通常将一个空对象提供给例程来构建它(使用循环、递归、条件等)。至于实践,至少有一个数据结构的框架总是一个好主意,它也可以用作编写函数的引用,该函数只需传递一些键名和值的变量即可生成整个事物。您将为该函数编写一个测试,该测试将返回您预测的对象等。

关于javascript - 在 Javascript 中构建复杂的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42236183/

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