Script to Rename the key of a JS object property [closed]

The following denotes a simple/basic script to rename the key of an object’s property:

const obj = { firstName: 'Sling', lastName: 'Academy' }; 
obj.name = obj.firstName; // create a new property with the same value
delete obj.firstName;     // delete the old property

While the above script may work fine for the JS object provided, it fails to work for a JS object of the type provided below:

const obj = {
  firstName: {
    address : '...',
    city    : '...',
    state   : '...',
    zip     : '...',
    phone   : '...'
  },
  secondName: {
    address : '...',
    city    : '...',
    state   : '...',
    zip     : '...',
    phone   : '...'
  },
  thirdName: {
    address : '...',
    city    : '...',
    state   : '...',
    zip     : '...',
    phone   : '...'
  },
  //...
}

As such, I am curious to know what changes need to be made to the script to rename a key or keys for a JS object of the type shown above to rename firstName, secondName, thirdName, …..

created a script to rename a key for a JS object property with nested property/values and it failed to rename the old key with the new one provided as intended.

  • 2

    it fails to work for a JS object of the type provided below:” I can’t reproduce it: jsbin.com/yizebihati/edit?js,console Note: I had to fix syntax error s because your object wasn’t correct. However, afterwards executing the code you showed in the first block did work. Please edit to include a minimal reproducible example of the code not working. And make sure the code runs.

    – 

  • if you change firstName to name, how do you change secondName and thirdName?

    – 

there is no particular problem for this…

const obj = 
  { firstName  : { address:'a1', city:'a2', state:'a3', zip:'a4', phone:'a5' } 
  , secondName : { address:'b1', city:'b2', state:'b3', zip:'b4', phone:'b5' } 
  , thirdName  : { address:'c1', city:'c2', state:'c3', zip:'c4', phone:'c5' } 
  } 
let index = 0;
for (let xName in obj)
  {
  obj[`name${++index}`] = obj[xName];
  delete obj[xName];
  }

console.log( obj );
.as-console-wrapper    { max-height: 100% !important;top: 0; }
.as-console-row::after { display: none !important;           }

Leave a Comment