javascripttypescriptecmascript-5spread-syntax

Alternative to array spread syntax in JavaScript


So I'm working with an old codebase that uses ES5 JavaScript, this means I cannot spread arrays

var listOfItems = [ ['item1', 'test', '1'], ['item2', 'test2', '2'] ];

var docDefinition = 
{
  style: 'piecesTable',
  table: {
    widths: ['*', '*', '*'],
    body: [
      [
        {text: 'Reference', style: 'tableHeader'}, 
        {text: 'Alias', style: 'tableHeader'},
        {text: 'Type', style: 'tableHeader'},
      ],
      ...listOfItems
    ]
  }
};

How can I spread listOfItems without using spread syntax as seen above ...listOfItems?

The listOfItems should be spread out to two separate arrays so essentially the result should be:

var docDefinition = 
{
  style: 'piecesTable',
  table: {
    widths: ['*', '*', '*'],
    body: [
      [
        {text: 'Reference', style: 'tableHeader'}, 
        {text: 'Alias', style: 'tableHeader'},
        {text: 'Type', style: 'tableHeader'},
      ],
      ['item1', 'test', '1'],
      ['item2', 'test2', '2']
    ]
  }
};

Solution

  • You can use concat() to merge into your body array

         var listOfItems = [ ['item1', 'test', '1'], ['item2', 'test2', '2'] ];
    
          var docDefinition = 
          {
            style: 'piecesTable',
            table: {
              widths: ['*', '*', '*'],
              body: [
                [
                  {text: 'Reference', style: 'tableHeader'}, 
                  {text: 'Alias', style: 'tableHeader'},
                  {text: 'Type', style: 'tableHeader'},
                ],
                
              ].concat(listOfItems)
            }
          };
          
          console.log(docDefinition)