javascriptobjectspread-syntax

Replace a key in an object while spreading


I have the below object,

const obj = {
  'a': 1,
  'b': 2,
  'c': 3,
  'd': 4,
  .
  .
  .
  .
  'z': 26
}

I want to have a new object which will contain all the keys as object obj, but instead of one specific key, I want it to be replaced with another key, say I want to omit key 'a' and replace it with 'new_a'. Below way doesn't remove the original key 'a'. Is there a way in which I can achieve it with aliasing? Or deleting key 'a' is the only option?

const obj2 = {
   ...obj,
   'new_a': 111
}

I want obj2 to be like this-

{
   'new_a': 111,
   'b': 2,
   'c': 3,
   .
   .
   .
   .
   'z': 26 
}

Solution

  • I can't think of a way to do it in a single step (single line, sure, but not a single step). Destructuring with rest followed by assignment does it nicely though:

    const {a, ...obj2} = obj;
    obj2.new_a = obj.a; // Or just `= a;`, either way
    

    Live Example:

    const obj = {
        'a': 1,
        'b': 2,
        'c': 3,
        'd': 4,
        // ...
        'z': 26
    };
    const {a, ...obj2} = obj;
    obj2.new_a = obj.a;
    console.log(obj2);