最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Alternative to array spread syntax in JavaScript - Stack Overflow

programmeradmin6浏览0评论

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

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']
    ]
  }
};
Share Improve this question edited Apr 6, 2023 at 17:22 VLAZ 29.2k9 gold badges63 silver badges84 bronze badges asked Dec 8, 2021 at 2:21 Eric BergmanEric Bergman 1,44312 gold badges47 silver badges86 bronze badges 9
  • 2 Is "concat" not what you want? – Dave Newton Commented Dec 8, 2021 at 2:27
  • 1 I mean how about after the docDefinition definition, you do something like listOfItems.forEach((item) => {docDefinition.table.body.push(item)} ? – CVerica Commented Dec 8, 2021 at 2:29
  • 1 That's a good suggestion, thanks @CVerica – Eric Bergman Commented Dec 8, 2021 at 2:33
  • 1 Glad I could help. It also looks like concat() that everyone is suggesting works as well, and may look a little cleaner. Good luck! – CVerica Commented Dec 8, 2021 at 2:37
  • 2 @MathewsSunny You are correct. forEach is es5, but the arrow function is not. So it would be listOfItems.forEach(function (item) { docDefinition.table.body.push(item)}) – CVerica Commented Dec 8, 2021 at 4:34
 |  Show 4 more ments

4 Answers 4

Reset to default 3

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)

Alternatives to spread syntax, seems like we have several options. But do we really have? Well it depends on the situation - lets focus on concat and push

concat

Pretty straight forward and a clean way as many suggests. The concat method merges the two array and returns the new array, so it returns a single array with all the elements, more like using spread. It won't affect the existing arrays since it returns new array, thus we can use it very easily. Let us see that in action:

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)

push

The push method unlike concat would add new items to the end of the array, so it mutates our base array to add new elements. The method would update the length of the array and will return the new length. In our case listOfItems is an array of arrays, not just array of elements, if we directly apply push it will push the array of arrays, that might be desirable in some situation but may not be in some other. Lets take a look at that :

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'},
      ],

    ],
  }
};

docDefinition.table.body.push(listOfItems);
console.log(docDefinition)

Here as we can see entire array is appended, still if we wanna remove that we could use the flat method to remove the sub-arrays to a depth, but it might affect code readability.

Instead, we could push array elements to the destination array by using forEach (or some other array traversal method) and push each items to the destination array. Here also the original array is mutated:

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.forEach(function(item){docDefinition.table.body.push(item)});
console.log(docDefinition)

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)
};

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.

发布评论

评论列表(0)

  1. 暂无评论