如何在 JavaScript 中将 2 个数组合并为 1 个对象


假设我们有两个长度相等的数组,需要编写一个将这两个数组映射到一个对象中的函数。第一个数组的对应元素将成为对象的对应键,而第二个数组的元素将成为值。

我们将缩减第一个数组,同时通过索引访问第二个数组的元素。此代码如下 −

示例

const keys = [
   'firstName',
   'lastName',
   'isEmployed',
   'occupation',
   'address',
   'salary',
   'expenditure'
];
const values = [
   'Hitesh',
   'Kumar',
   false,
   'Frontend Developer',
   'Tilak Nagar, New Delhi',
   90000,
   45000
];
const combineArrays = (first, second) => {
   return first.reduce((acc, val, ind) => {
      acc[val] = second[ind];
      return acc;
   }, {});
};
console.log(combineArrays(keys, values));

输出

控制台中的输出如下 −

{
   firstName: 'Hitesh',
   lastName: 'Kumar',
   isEmployed: false,
   occupation: 'Frontend Developer',
   address: 'Tilak Nagar, New Delhi',
   salary: 90000,
   expenditure: 45000
}

更新于:2020-08-21

673 次阅读

开启你的 职业生涯

通过完成课程取得认证

开始
广告
© . All rights reserved.