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
}
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
}
Share
Improve this question
edited Oct 24, 2024 at 5:48
DarkBee
15.5k8 gold badges72 silver badges117 bronze badges
asked Feb 17, 2021 at 13:22
Frosted CupcakeFrosted Cupcake
1,9704 gold badges22 silver badges51 bronze badges
1
-
If they key doesn't need to be
new_a
you can just simply overwrite it likeconst obj2 = { ...obj, 'a': 111 }
– StackByMe Commented Feb 17, 2021 at 13:28
4 Answers
Reset to default 3I 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);
if you don't want new_a to have the same value as a then:
const obj2 = { ...obj, new_a: 111 };
delete obj2["a"];
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.
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);