Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS rename an object key, while preserving its position in the object

My javascript object looks like this:

const someObj = {
  arr1: ["str1", "str2"],
  arr2: ["str3", "str4"]
}

In attempting to rename a key (e.g. arr1), I end up deleting the existing key and writing a new key with the original value. The order of obj changes.

someObj = {
  arr2: ["str3", "str4"],
  renamedarr1: ["str1", "str2"]
}

How do I rename a key while preserving the key order?

like image 991
U Rogel Avatar asked Jan 03 '18 17:01

U Rogel


People also ask

How do you rename an object key?

To rename a key in an object:Use bracket notation to assign the value of the old key to the new key. Use the delete operator to delete the old key. The object will contain only the key with the new name.

Can we change object key in JavaScript?

JavaScript doesn't provide an inbuilt function to rename an object key.


2 Answers

In the end it was solved in a js-vanila way rather than a react way.

In case somebody would look for a similar solution, I am posting the code I ended up using. Inspired by Luke's idea:

const renameObjKey = ({oldObj, oldKey, newKey}) => {
  const keys = Object.keys(oldObj);
  const newObj = keys.reduce((acc, val)=>{
    if(val === oldKey){
        acc[newKey] = oldObj[oldKey];
    }
    else {
        acc[val] = oldObj[val];
    }
    return acc;
  }, {});

  return newObj;
};
like image 177
U Rogel Avatar answered Sep 20 '22 12:09

U Rogel


You might want to consider reducing the array of keys into a new object. To do this, you need also to know which key changed to what.

  1. Reduce the array of keys
  2. use a reducer which checks for a key change, and change it if necessary.
  3. add the key to the object with the value

After that you have a Object with the order you had before, and possibly a changed key is still at the same position

Something like this might work (not tested)

const changedKeyMap = {"previousKey": "newKey"};
const keys = Object.keys(this.state.obj);
const content = e.target.value;
const result = keys.reduce((acc, val) => {
    // modify key, if necessary
    if (!!changedKeyMap[val]) {
        val = changedKeyMap[val];
    }
    acc[val] = content;
    // or acc[val] = this.state.obj[val] ? 
    return acc;
}, {});

As you can see, you need to keep track of how you changed a key (changedKeyMap). The reduce function just iterates over all keys in correct order and adds them to a newly created object. if a key is changed, you can check it in the changedKeyMap and replace it. It will still be at the correct position

like image 26
Luke Avatar answered Sep 18 '22 12:09

Luke