简体   繁体   English

将JS单行对象实例化为块实例化

[英]Convert JS single-line object instantiation to block instantiation

I have user-specified input that looks like this: 我有用户指定的输入,如下所示:

outerObject = {};
outerObject.innerObject = {};
outerObject.innerObject.key = 'value';
outerObject.innerObject.exampleTwo = 2;

Repeat that general pattern for a couple thousand lines, and you see how this looks a little tedious and is hard to maintain. 重复该常规模式几千行,您会看到它看起来有点乏味并且难以维护。 What I'd like to do is output these lines into something like this: 我想做的就是将这些行输出为如下内容:

outerObject = {
    innerObject: {
        key: 'value',
        exampleTwo: 2
    }
};

Is there an existing library to convert the single-line object creations into the block creation shown above? 是否有一个现有的库可将单行对象创建转换为上面显示的块创建? And if not, mind taking a stab at code that could? 如果不是,介意刺破可能的代码吗? I'm so fundamentally confused at where to start that I can't even figure out how to nest objects, so any help would be great. 我对从哪里开始感到非常困惑,以至于我什至都不知道如何嵌套对象,因此任何帮助都会很棒。

EDIT: I stumbled upon this accepted answer for a different issue . 编辑:我偶然发现了这个被接受的答案,是另一个问题 It appears to format an object the way I want after splitting the value and key from each of the four lines in that first block. 从第一个块的四行中的每一行中拆分出值和键后,似乎可以按照我想要的方式格式化对象。 It does not include any sort of output formatting, however... 它不包括任何形式的输出格式,但是...

This method only works when all objects are static/JSON-like, meaning no functions or anything 仅当所有对象都是静态/类似于JSON时,此方法才有效

You could just evaluate your input like this in the browser (or the browser console or any js context, like Node): 您可以在浏览器(或浏览器控制台或任何js上下文,例如Node)中像这样评估您的输入:

<script>
    outerObject = {};
    outerObject.innerObject = {};
    outerObject.innerObject.key = 'value';
    outerObject.innerObject.exampleTwo = 2;
</script>

Then just JSON.stringify(outerObject, null, ' ') which will return 然后只是JSON.stringify(outerObject, null, ' ')将返回

"{
    "innerObject": {
        "key": "value",
        "exampleTwo": 2
    }
}"

All you do next is append "outerObject = " in front 接下来要做的就是在前面附加"outerObject = "

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM