首页 > 解决方案 > Javascript - 组合数组并保持相同的索引

问题描述

我正在尝试组合 3 个对象数组,同时保持原始数组的相同索引。我可以通过使用一种spread operator方法来实现这一点。我目前的问题是,由于它的兼容性,我在 Internet Explorer 上遇到了问题。如果不使用方法,我一直无法找到另一种spread operator方法。这可以通过与 Internet Explorer 兼容的方法来完成吗?

这是我正在使用的当前代码:

const revenueArr = [{title: 'online', revenue: 34321, revenueGrowth: 3.2},{title: 'retail', revenue: 321, revenueGrowth: 1.2} ] 

const employArr = [ { employGrowth: 0.2 }, {employGrowth: -1.2} ]


const businessArr = [ {businessGrowth: 2.8}, {businessGrowth: 1.6} ] 


const allData = revenueArr.map((it, index) => {
    return { ...it, ...employArr[index], ...businessArr[index]}
}) 

console.log(allData)

我的预期结果是上面代码片段中的 console.log,其中对象的第一个索引在将它们组合在一起后仍然是第一个索引。如:

[
  {
    "title": "online",
    "revenue": 34321,
    "revenueGrowth": 3.2,
    "employGrowth": 0.2,
    "businessGrowth": 2.8
  },
  {
    "title": "retail",
    "revenue": 321,
    "revenueGrowth": 1.2,
    "employGrowth": -1.2,
    "businessGrowth": 1.6
  }
]

标签: javascriptarrayscross-browser

解决方案


您可以Object.assign()用作扩展运算符的替代品。Object.assign()在 Internet Explorer 中也不可用,但您可以使用polyfill,因为它不是新语法。

// Object.assign polyfill for Internet Explorer

if (typeof Object.assign !== 'function') {
  // Must be writable: true, enumerable: false, configurable: true
  Object.defineProperty(Object, "assign", {
    value: function assign(target, varArgs) { // .length of function is 2
      'use strict';
      if (target === null || target === undefined) {
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var to = Object(target);

      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource !== null && nextSource !== undefined) { 
          for (var nextKey in nextSource) {
            // Avoid bugs when hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
}

const revenueArr = [{title: 'online', revenue: 34321, revenueGrowth: 3.2},{title: 'retail', revenue: 321, revenueGrowth: 1.2} ] 

const employArr = [ { employGrowth: 0.2 }, {employGrowth: -1.2} ]


const businessArr = [ {businessGrowth: 2.8}, {businessGrowth: 1.6} ] 


const allData = revenueArr.map((it, index) => {
    return Object.assign({}, it, employArr[index], businessArr[index]);
}) 

console.log(allData)


推荐阅读