- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate through Object keys and manipulate the key values in JavaScript
Suppose, we have an array of objects like this −
const arr = [ { col1: ["a", "b"], col2: ["c", "d"] }, { col1: ["e", "f"], col2: ["g", "h"] } ];
We are required to write a JavaScript function that takes in one such array and returns the following output.
const output = [ { col1: "b", col2: "d" }, { col1: "f", col2: "h" } ];
Basically, we want to convert the Object keys Value which is an array initially to a single value and that value will be the second element of the Object keys array.
The code for this will be −
const arr = [ { col1: ["a", "b"], col2: ["c", "d"] }, { col1: ["e", "f"], col2: ["g", "h"] } ]; const reduceArray = (arr = []) => { const res = arr.reduce((s,a) => { const obj = {}; Object.keys(a).map(function(c) { obj[c] = a[c][1]; }); s.push(obj); return s; }, []); return res; }; console.log(reduceArray(arr));
And the output in the console will be −
[ { col1: 'b', col2: 'd' }, { col1: 'f', col2: 'h' } ]
Advertisements