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.

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

  1. Would this work?
    If you’re just mapping it to new key names.

    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"}];
    
    const test = data.map((obj) => ({
      id: obj["result.rows.author_id"],
      name: obj["result.rows.name"],
      orcid: obj["result.rows.orcid"]
    }))
    
    console.log(test)
    Reply
  2. If the set of keys to read/write are dynamic, then you’ll have to iterate them for each object you want to translate: the number of changes to perform is equal to the number of objects times the number of keys. By consequence you’ll have a nested loop.

    However, maybe you would like to make the code more functional programming style, so that the inner loop is also a kind of mapper that returns the new object format:

    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 mappedData = data.map(obj =>
      Object.fromEntries(OKeys.map((k, i) => [DKeys[i], obj[k]]))
    );
    
    console.log(mappedData);
    Reply

Leave a Comment