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
Iterate through Object keys and manipulate the key values in JavaScript
When working with arrays of objects in JavaScript, you often need to iterate through object keys and transform their values. This article demonstrates how to extract specific elements from array values within objects.
Problem Statement
Suppose we have an array of objects where each property contains an array of values:
const arr = [
{
col1: ["a", "b"],
col2: ["c", "d"]
},
{
col1: ["e", "f"],
col2: ["g", "h"]
}
];
Our goal is to transform this array so that each object's property values become the second element (index 1) of their respective arrays:
const output = [
{
col1: "b",
col2: "d"
},
{
col1: "f",
col2: "h"
}
];
Using Array.reduce() and Object.keys()
Here's a solution that combines Array.reduce() with Object.keys() to iterate through each object and transform its properties:
const arr = [
{
col1: ["a", "b"],
col2: ["c", "d"]
},
{
col1: ["e", "f"],
col2: ["g", "h"]
}
];
const reduceArray = (arr = []) => {
const res = arr.reduce((accumulator, currentObject) => {
const newObj = {};
Object.keys(currentObject).forEach(key => {
newObj[key] = currentObject[key][1]; // Get second element
});
accumulator.push(newObj);
return accumulator;
}, []);
return res;
};
console.log(reduceArray(arr));
[ { col1: 'b', col2: 'd' }, { col1: 'f', col2: 'h' } ]
Using Array.map() (Alternative Approach)
A more concise approach using Array.map() for the outer transformation:
const arr = [
{
col1: ["a", "b"],
col2: ["c", "d"]
},
{
col1: ["e", "f"],
col2: ["g", "h"]
}
];
const transformArray = (arr = []) => {
return arr.map(obj => {
const newObj = {};
Object.keys(obj).forEach(key => {
newObj[key] = obj[key][1];
});
return newObj;
});
};
console.log(transformArray(arr));
[ { col1: 'b', col2: 'd' }, { col1: 'f', col2: 'h' } ]
How It Works
The solution works in these steps:
-
Iterate through each object in the array using
reduce()ormap() -
Get all property keys of the current object using
Object.keys() -
Transform each property by accessing the second element (
[1]) of its array value - Build a new object with the transformed values
- Return the transformed array
Key Points
-
Object.keys()returns an array of object property names -
Array.reduce()accumulates results into a new array -
Array.map()provides a cleaner transformation approach - Both methods preserve the original array structure while transforming values
Conclusion
This approach demonstrates how to iterate through object keys and manipulate their values effectively. Use Object.keys() combined with Array.map() or Array.reduce() to transform complex nested data structures in JavaScript.
