简体   繁体   中英

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

You could just evaluate your input like this in the browser (or the browser console or any js context, like Node):

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

Then just JSON.stringify(outerObject, null, ' ') which will return

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

All you do next is append "outerObject = " in front

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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