Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename key most efficiently in array of items in javascript?

Tags:

javascript

I have an array of 10000 objects. Each object is like this:

{"id":5, "name": "Jordin Sparks}

What is the most efficient and fastest way for me to rename keys such that every object in the array becomes:

{"num":5, "fullname": "Jordin Sparks"}

In other words, "id" property is renamed to "num" and the "name" property for each object is renamed to "fullname".

like image 948
Rolando Avatar asked Nov 09 '15 02:11

Rolando


Video Answer


2 Answers

Brute force approach. Convert to string, rename fields and parse to JSON

var src = {"id":5, "name": "Jordin Sparks"};

var str = JSON.stringify(src);

var rst = JSON.parse(str.replace(/"id"/g, '"num"').replace(/"name"/g, '"fullname"'));
console.debug(rst);

Edit: modify replace to global.

like image 106
Jules Avatar answered Oct 14 '22 22:10

Jules


Personally, I would do it like this.

function renameKeys(arr, nameMap) {
  // loop around our array of objects
  for(var i = 0; i < arr.length; i++) {
    var obj = arr[i];
    // loop around our name mappings
    for(var j = 0; j < nameMap.length; j++) {
       var thisMap = nameMap[j];
       if(obj.hasOwnProperty(thisMap.from)) {
         // found matching name
         obj[thisMap.to] = obj[thisMap.from];
         delete obj[thisMap.from];
       }
    }
  }
}

You would call it like so, where myArray is your array of objects.

renameKeys(myArray, [ 
  {from: "id", to: "num" }, 
  { from: "name", to: "fullname" } 
]);

Has the advantage that it is reusable for any number of name re-mappings. Doesn't modify native prototypes. And only iterates once around the array, no matter how many re-mappings take place.

like image 29
Shaun Avatar answered Oct 14 '22 22:10

Shaun