Search code examples
javascriptarraysjsonloopsiterator

rename key in array of objects using javascript


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

Here is the error enter image description here

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

enter image description here


Solution

  • You could take an object for the replacements and map the single objects with replaced properties.

    const
        input = [{ "p1": [ 1, 0 ] }, { "p2": [ 1, 6 ] }, { "total": [ 0, 4 ] }, { "p3plus": [ 0, 2 ] }],
        replacements = { p1: 'P1', p2: 'P2', total: 'Total', p3plus: 'P3+' },
        result = input.map(o => Object.fromEntries(Object
            .entries(o)
            .map(([k, v]) => [replacements[k] || k, v])
        ));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }