【问题标题】:Javascript - Combining arrays and keeping same indexesJavascript - 组合数组并保持相同的索引
【发布时间】:2020-08-04 00:02:20
【问题描述】:

我正在尝试组合 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)

我的预期结果是上面代码 sn-p 中的 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
  }
]

【问题讨论】:

    标签: javascript arrays cross-browser


    【解决方案1】:

    您可以使用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)

    【讨论】:

    • 使用 polyfill 时是否像将代码从 mdn 复制并粘贴到我的代码中一样简单?还是我根据您提供的代码 sn-p 进行更改?不确定如何实现 polyfill
    • 这里以 jsfiddle jsfiddle.net/r842yfgt 为例。
    • polyfill 只是在 Object.assign() 不可用时定义它。这是我的 sn-p 中使用该函数代替传播的代码的补充。
    • 您需要在尝试调用它之前定义polyfill。它应该在脚本的开头。
    【解决方案2】:

    Object.assign 应该为您提供相同的输出,并支持旧版浏览器。

    const allData1 = revenueArr.map((it, index) => {
      return { ...it, ...employArr[index], ...businessArr[index] } // using spread
    })
    
    console.log(allData1)
    
    const allData2 = revenueArr.map((it, index) => {
      return Object.assign({}, it, employArr[index], businessArr[index]) // using Object.assign
    })
    
    console.log(allData2) // same as allData1
    

    您可能会发现这很有用https://thecodebarbarian.com/object-assign-vs-object-spread.html

    【讨论】:

      【解决方案3】:

      这应该在所有地方都得到支持:

      revenueArr.map((it, index) => {
          let r = {};
          for(let [key, value] of Object.entries(it))
              r[key] = value;
          for(let [key, value] of Object.entries(employArr[index]))
              r[key] = value;
          for(let [key, value] of Object.entries(businessArr[index]))
              r[key] = value;
          return r;
      }) 
      

      使用以下 polyfill:

      if (!Object.entries)
        Object.entries = function( obj ){
          var ownProps = Object.keys( obj ),
              i = ownProps.length,
              resArray = new Array(i); // preallocate the Array
          while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
      
          return resArray;
        };
      

      (学分:@jfriend00

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-02
        • 2016-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多