Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to merge an array with an object where values are arrays - JavaScript
In JavaScript, you can merge an array with an object containing array values by mapping array elements to object keys sequentially. This creates a new structure where each group contains key-value pairs.
Problem Statement
Given an array of values and an object with arrays as values, we want to distribute the array values across the object's arrays as keys:
const arr = [1, 2, 3, 4, 5];
const obj = {
group1: ["Ram", "Mohan", "Shyam"],
group2: ["Jai", "Dinesh"],
};
// Expected output:
const expected = {
group1: {
"Ram": 1,
"Mohan": 2,
"Shyam": 3
},
group2: {
"Jai": 4,
"Dinesh": 5
}
};
Using Manual Iteration
This approach uses a simple loop to distribute array values across object groups:
const arr = [1, 2, 3, 4, 5];
const obj = {
group1: ["Ram", "Mohan", "Shyam"],
group2: ["Jai", "Dinesh"],
};
const zipObject = (arr, obj) => {
const res = {};
let valueIndex = 0;
for (const groupKey in obj) {
res[groupKey] = {};
const groupArray = obj[groupKey];
for (let i = 0; i
{
group1: { Ram: 1, Mohan: 2, Shyam: 3 },
group2: { Jai: 4, Dinesh: 5 }
}
Using Array Methods
A more functional approach using reduce() and array methods:
const arr = [1, 2, 3, 4, 5];
const obj = {
group1: ["Ram", "Mohan", "Shyam"],
group2: ["Jai", "Dinesh"],
};
const zipObjectFunctional = (arr, obj) => {
let valueIndex = 0;
return Object.keys(obj).reduce((result, groupKey) => {
result[groupKey] = obj[groupKey].reduce((group, name) => {
if (valueIndex
{
group1: { Ram: 1, Mohan: 2, Shyam: 3 },
group2: { Jai: 4, Dinesh: 5 }
}
Handling Edge Cases
Enhanced version that handles mismatched array lengths:
const zipObjectSafe = (arr, obj) => {
const res = {};
let valueIndex = 0;
for (const groupKey in obj) {
res[groupKey] = {};
const groupArray = obj[groupKey];
for (const name of groupArray) {
if (valueIndex
{
group1: { Ram: 1, Mohan: 2, Shyam: null },
group2: { Jai: null, Dinesh: null }
}
Comparison
| Method | Readability | Performance | Edge Case Handling |
|---|---|---|---|
| Manual Iteration | Good | Fast | Basic |
| Functional Approach | Excellent | Slower | Basic |
| Safe Version | Good | Fast | Comprehensive |
Conclusion
Use manual iteration for performance-critical applications or the functional approach for cleaner, more maintainable code. Always consider edge cases like mismatched array lengths in production code.
