如何在 JavaScript 中将 2 个数组合并为 1 个对象
javascriptweb developmentobject oriented programming更新于 2025/10/1 18:20:17
假设我们有两个长度相等的数组,需要编写一个函数将两个数组映射到一个对象中。第一个数组的相应元素将成为对象的相应键,第二个数组的元素将成为值。
我们将减少第一个数组,同时通过索引访问第二个数组的元素。此代码如下 −
示例
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
}
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

