How to map array of objects, mapping their keys without nested loops?

How to map an array of objects to another array of objects with multiple key changes? It is given what keys I have to change before the loop starts.

I am doing it using two loops: one for map, and another for key changes.

Example:

var data = [{"result.rows.author_id":1,"result.rows.name":"Ames T","result.rows.orcid":""},{"result.rows.author_id":2,"result.rows.name":"Argasinska J","result.rows.orcid":"0000-0003-2678-2824"}];
var OKeys= ["result.rows.author_id", "result.rows.name", "result.rows.orcid"];
var DKeys= ["id", "name", "orcid"];
var countLength = OKeys.length;

var mappedData = data.map(function(obj) {
  var newObj = {};
  /* How we can remove this loop and still map to new keys */
  for(var i=0;i<countLength;i++) {
      newObj[DKeys[i]] = obj[OKeys[i]];
  }
  return newObj;
});

console.log(mappedData);

I want to know is there any way I can remove countLength loop and still be able to map to new keys or any other way to optimize this two nested loop in one loop.

16 thoughts on “How to map array of objects, mapping their keys without nested loops?”

Leave a Comment