Home > Enterprise >  Javascript Spread Operator Alternative
Javascript Spread Operator Alternative

Time:12-08

So I'm working with an old codebase that uses javascript es5, this means I cannot use the spread operator

          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 the spread operator 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']
              ]
            }
          };

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Try with concat():

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

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

CodePudding user response:

If you're just trying to add an item to the front of a list, you can always use Array.prototype.unshift(), and for the back there's always Array.prototype.push(), or even Array.prototype.concat(). In general, though there is no polyfill for the spread operator, there are alternative ways of inserting items into arrays at different indices that you can use instead.

  • Related