Search code examples
javascriptcode-formattingjs-beautify

JS array of objects formatting


I'm trying to set up a custom formatter using the js-beautify node package, but I'm running into an issue when formatting an array of objects. I want my output to look like this:

{
  someFunction: function() {

  },

  arr: [{
    thing: 1
  }, {
    one: 2
  }]
}

You'll notice that my braces are on the same line as another brace or bracket. However, I've noticed that if my code contains a format like this, it formats incorrectly:

// Formatted input
{
    someFunction: function() {

    },

    arr: [{
        thing: 1
    },
     {
        one: 2
    }]
}

// Formatted output
{
    someFunction: function() {

    },

    arr: [{
            thing: 1
        },
        {
            one: 2
        }
    ]
}

I thought "brace_style": "end-expand" would be what I wanted, but it appears not to work for this case. It's weird because if I had something like the below, it would format properly on the online beautifier:

{
    someFunction: function() {

    },

    arr: [{
        thing: 1
    },     {
        one: 2
    }]
}

Anybody have any suggestions how to get my desired output? I'm assuming there's some config property I can set. Also, if someone has a better node package or formatter, I'd be entertaining that as well.

EDIT From Adnan Sharif's first suggestion, it looks like "preserve_newlines": true is the reason why this is happening, but if I remove that, then I lose all of my newlines... this seems a little troubling if I can't preserve all of my newlines due to brace formatting.


Solution

  • An alternative to this would be to use ESLint and my package's overrides for the rules array-bracket-newline and array-element-newline.