I have a simple array of objects as shown below
let input = [
{ "p1": [ 1, 0 ] },
{ "p2": [ 1, 6 ] },
{ "total": [ 0, 4 ] },
{ "p3plus": [ 0, 2 ] }
]
All i want to do is just rename the keys of this array of objects. so my final output should be as shown below. Basically i am renaming p1, p2, p3plus and total with P1, P2, P3+ and Total.
let output = [
{ "P1": [ 1, 0 ] },
{ "P2": [ 1, 6 ] },
{ "Total": [ 0, 4 ] },
{ "P3+": [ 0, 2 ] }
]
I tried the following code
const output = input.map(({
p1: P1,
p2: P2,
p3plus: P3+,
total: Total,
...rest
}) => ({
P1,
P2,
P3+,
Total,
...rest
}));
This code doesnot work primarily because i am trying to put P3+
and it errors out during compilation. Even if i skip renaming p3plus
, the output is not as expected because it keeps adding undefined to the final output. Can someone point to me where i am going wrong
also, if i dont rename p3Plus
and go ahead and rename other two, i see undefined objects which are not needed. how can i eliminate getting those undefined objects
2
Answers
You could take an object for the replacements and map the single objects with replaced properties.
You cannot renamed the destructured
p3plus
variableP3+
, since a plus sign (+
) is not a legal variable name character.You will need to assign it via:
{ 'P3+': p3plus }
Here is a modified version of Nina’s code for clarity: