How to rename a key most efficiently in an array of elements in javascript?

I have an array of 10,000 objects. Each object is as follows:

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

What is the most efficient and fastest way to rename keys so that each object in the array becomes the following:

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

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

+5
source share
5 answers

I have no idea if this is really effective, but here is my attempt.

 for(var i = arr.length; i--; ){ var obj = arr[i]; obj.num = obj.id; obj.fullname = obj.name; delete obj.id; delete obj.name; } 
+1
source

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 where myArray is your array of objects.

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

It has the advantage that it can be reused for any number of re-name mappings. Does not modify its own prototypes. And it only repeats itself once around the array, regardless of how many repeated mappings occur.

+1
source

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: change the replacement to global.

+1
source

From fooobar.com/questions/41346 / ... :

 Object.prototype.renameProperty = function (oldName, newName) { // Do nothing if the names are the same if (oldName == newName) { return this; } // Check for the old property name to avoid a ReferenceError in strict mode. if (this.hasOwnProperty(oldName)) { this[newName] = this[oldName]; delete this[oldName]; } return this; }; 

You will run objectOf1000.renameProperty('id', 'num') and objectOf1000.renameProperty('name', 'full name')

0
source
 arr.map(function (item) { return { num: item.id, fullname: item.name } }); 
0
source

Source: https://habr.com/ru/post/1235503/


All Articles