javascript - 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
}
]
解决方案
您可以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)
推荐阅读
- javascript - 在 MongoDB 中使用 JS 函数和正则表达式来匹配字段
- laravel - 共享中间件中的惯性句柄 null
- sql - 计算列的中位数并将它们存储在 BQ 表中
- optaplanner - OptaPlanner,Score计算速度会太低
- javascript - window.open(url) 方法重新加载页面
- html - HTMLAudioElement 作为 JS 音频
- laravel - Laravel - 使用惯性访问路由来填充 Vuejs3 中的道具
- laravel-5 - 如何在数据透视表上应用过滤器?
- reactjs - 我在 package.json 中添加了一个代理,但应用程序没有使用该代理
- reactjs - TypeScript React:使用 JSX.Element 类型的静态属性(未初始化的组件)扩展 React.FC 时摆脱 TS(2339)