Giả sử chúng ta có hai mảng cùng độ dài và cần viết hàm ánh xạ hai mảng thành một object. Phần tử tương ứng của mảng đầu tiên thành khóa, mảng thứ hai thành giá trị.
Chúng ta sẽ reduce mảng đầu tiên, đồng thời truy cập phần tử mảng thứ hai bằng chỉ số. Mã như sau:
Ví dụ
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));Kết quả
Đầu ra trong console sẽ là:
{
firstName: 'Hitesh',
lastName: 'Kumar',
isEmployed: false,
occupation: 'Frontend Developer',
address: 'Tilak Nagar, New Delhi',
salary: 90000,
expenditure: 45000
}