Iterate through Object keys and manipulate the key values in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' } ]
raja
Published on 20-Nov-2020 13:19:08
Advertisements