skip to Main Content

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

2

Answers


  1. 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; }
    Login or Signup to reply.
  2. You cannot renamed the destructured p3plus variable P3+, since a plus sign (+) is not a legal variable name character.

    You will need to assign it via: { 'P3+': p3plus }

    const input = [
      { "p1"     : [ 1, 0 ] },
      { "p2"     : [ 1, 6 ] },
      { "total"  : [ 0, 4 ] },
      { "p3plus" : [ 0, 2 ] }
    ];
    
    const output = input.map(({
      p1: P1,
      p2: P2,
      p3plus, // Keep as `p3plus` for now...
      total: Total,
      ...rest
    }) => ({
      P1,
      P2,
      'P3+': p3plus, // Re-key here, since the '+' is not a valid variable name
      Total, 
      ...rest
    }));
    
    console.log(...output.map(JSON.stringify));
    .as-console-wrapper { top: 0; max-height: 100% !important; }

    Here is a modified version of Nina’s code for clarity:

    const renameKeys = (objArr, keyReplacements) => {
      return objArr.map(obj => {
        const entries = Object.entries(obj)
          .map(([originalKey, originalValue]) => [
            keyReplacements[originalKey] ?? originalKey,
            originalValue
          ]);
        return Object.fromEntries(entries); // Back to object
      });
    };
    
    const input = [
      { "p1"     : [ 1, 0 ] },
      { "p2"     : [ 1, 6 ] },
      { "total"  : [ 0, 4 ] },
      { "p3plus" : [ 0, 2 ] }
    ];
    
    const replacements = {
      p1     : 'P1',
      p2     : 'P2',
      total  : 'Total',
      p3plus : 'P3+'
    };
    
    const output = renameKeys(input, replacements);
    
    console.log(...input.map(JSON.stringify));  // Before
    console.log(...output.map(JSON.stringify)); // After
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search