3

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 
}
Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42
  • If they key doesn't need to be `new_a` you can just simply overwrite it like `const obj2 = { ...obj, 'a': 111 }` – Reyno Feb 17 '21 at 13:28

4 Answers4

3

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);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

if you don't want new_a to have the same value as a then:

const obj2 = { ...obj, new_a: 111 };
delete obj2["a"];
TomBonynge
  • 303
  • 1
  • 5
1

Perhaps not the cleanest approach, but a single-liner:

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

let obj2 = { 
    'new_a': 111, 
    ...Object.fromEntries(Object.entries(obj).filter(([key]) => key !== 'a'))
};

console.log(obj2);

This way you don't have to delete any key and you don't have to "copy" the original a to the new object.

NullDev
  • 6,739
  • 4
  • 30
  • 54
0

You can use an iife and the object rest spread operator to collect all but the renamed properties and spread to add them to a new object. mdn docs for reference.

const obj2 = (({a: newA, ...rest}) => ({newA, ...rest}))(obj)


For readabilities sake you might want to consider writing adapter functions, it's quite and describes the transformation of the objects properties pretty well.

const obj = {a: 1, b: 2, c:3, d: 4};

const adapter = ({a: newA, ...rest}) => ({newA, ...rest});

const obj2 = {
  ...adapter(obj), 
}

console.log(obj2);
Moritz Roessler
  • 8,542
  • 26
  • 51