changing the name of a key in an array of objects with javascript

I have an array of objects with keys and values as follows:

let input = [
    { "b1": [ 1, 0 ] },
    { "b2": [ 1, 6 ] },
    { "total": [ 0, 4 ] },
    { "b3plus": [ 0, 2 ] }
]

I want to rename the keys of this array of objects so that the final output looks like this:

let output = [
    { "B1": [ 1, 0 ] },
    { "B2": [ 1, 6 ] },
    { "Total": [ 0, 4 ] },
    { "B3+": [ 0, 2 ] }
]

The code I tried is as follows:

const output = input.map(({
  b1: B1,
  b2: B2,
  b3plus: B3plus,
  total: Total,

  ...rest
}) => ({
  B1,
  B2,
  B3plus, 
  Total, 
  ...rest
}));

However, this code is not successful because renaming B3+ causes an error during compilation. Even if I skip renaming b3plus, the output is not as expected because undefined objects are added. Can someone help me identify where I am making a mistake?

Here is the error https://i.sstatic.net/nbGG97PN.png

If I do not rename b3Plus and proceed with renaming the other keys, I see unnecessary undefined objects. How can I avoid including those undefined objects?

https://i.sstatic.net/jt7nkG1F.png

Answer №1

One approach is to use an object for the replacements and map the individual objects with the updated 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; }

Answer №2

You are unable to change the name of the deconstructed p3plus variable to P3+ because the plus sign (+) is not allowed in a variable name.

To assign it, you should use: { '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; }

Below is an amended version of Nina's code to enhance 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; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Use JQuery to Display Elements with a Vague Name?

Several PHP-generated divs are structured as follows: <div style="width:215px;height:305px;background-color: rgba(255, 255, 255, 0.5);background-position: 0px 0px;background-repeat: no-repeat;background-size: 215px 305px;display:none;position:fixed;top ...

Discord.js Discord bot error: 'gateway' down

Hello, I could really use some assistance. Two days back, my discord bot began crashing unexpectedly. The error that keeps popping up is: events.js:367 throw err; // Unhandled 'error' event ^ Error [ERR_UNHANDLED_ERROR]: An uncau ...

Modify the width of the progress bar in Bootstrap using AngularJS

I'm new to AngularJS and I'm attempting to dynamically update the width of a progress bar based on changes in my controller. Here is what I currently have: <span id="percentage">$ {{getTotal()}} ({{getPercentage()}}%)</span> <div ...

I encountered an error in the console stating, "Uncaught ReferenceError: req is not defined," while trying to access req.query.id

Encountering the error 'Uncaught ReferenceError: req is not defined' when attempting to use req.query.id. Below is the content of my index.js file: const express = require("express"); const path = require("path"); const port = 8000; ...

Different option for key press identification

My JavaScript skills are still at a beginner level and I've come across a bug that's causing me trouble. The issue is with keyCode not working on mobile devices (Chrome). It seems that mobile devices do not support keyCode. I think I could use ...

Launch the file explorer using JavaScript/HTML

Is there a way to launch a real explorer window instead of the browser's directory look? For example, like the windows key + e window... Is there a method using html or JavaScript? I've noticed it in a Firefox add-on called new tab king, but I c ...

Submitting Forms with XMLHttpRequest

I'm trying to utilize XMLHttpRequest in order to retrieve the response from a remote PHP file and showcase it on my webpage. The issue I'm facing is that the form's data isn't being submitted to the remote PHP page. Any suggestions on ...

What is the best way to organize a Meteor codebase when incorporating external scripts?

I'm interested to know if anyone has come up with a recommended approach for organizing Meteor applications that involve external shell scripts or other backend processes separate from the node.js server and client-side js code. For example, I have a ...

What steps can a web developer take to view user console errors?

Is there an effective method for a web developer to receive notifications of console errors logged by other authorized users? I am currently working with Express, Passport, and MongoDB. These errors may occur on either the client or server side. One approa ...

Error occurred within node while attempting to create a directory using mkdirsync

I wrote some code. try{ var Storage = multer.diskStorage({ destination: function (req, file, callback) { fs.mkdirSync('/home/data/' + file.originalname, { recursive: true }, (error) => { ...

Cannot use MaterialUI Textfield/Input on iPhone devices

Recently, I encountered an issue with iPhone users being unable to type in Textfield or Input components in apps developed using MaterialUI, even when the value and setValue were properly configured. To solve this problem for each component individually, ...

creating a post action using Node.js with Express and Angular

Process Overview I have an Angular post that communicates with my Node.js Express backend to send data to an API. My goal is to redirect the user to a different Angular page upon successful post, or display an error message if the post fails. One approac ...

What is the best way to structure my JSON data?

Below is an example of JSON data: [ {"name":"userID","value":"123"}, {"name":"score","value":"95"}, {"name":"dob","value":"20-Feb-1990"}, {"name":"location","value":"New York"} ] I am looking to transform this JSON into: { "userID":"123", "s ...

Increasing the checkout date by one day: A step-by-step guide

I am looking to extend the checkout period by adding 1 more day, ensuring that the end date is always greater than the start date. Below are my custom codes for implementing the bootstrap datepicker: $(function() { $('#datetimepicker1').da ...

Today's Date Bootstrap Form

How can I show today's date in a Bootstrap form with the input type set to 'date' and another input with the type set to 'time'? Most solutions I've found involve changing the input type to 'text'. Is there a way to ...

Incorporating events into a calendar using JSON in IOS Titanium

Is there a way to prevent duplicate entries when adding events to the iOS calendar from a JSON file timetable? I want to avoid adding events if there is already an existing event on the same date. How can this code be modified to achieve that? var fileN ...

Extract data from the HTML source code in JavaScript and transfer it to a personalized JavaScript variable within Google Tag Manager

Running an e-commerce website on Prestashop and facing an issue with data layer set up. Instead of a standard data layer, the platform generates a javascript variable called MBG for Enhanced E-Commerce implementation. <script type="text/javascript"> ...

Every time Lodash.uniqueId is called, it consistently generates the value of

Consider using the lodash library, specifically version 4.17.11. _.uniqueId() seems to consistently output 1 instead of a random three-digit number. Similarly, _.uniqueId('prefix') always returns prefix1. Do you see this as a potential issue? ...

Setting Start and End Dates in Bootstrap Vue Datepicker to Ensure End Date is After Start Date

My Vue.js form includes two BootstrapVue datepickers for holiday management. Users can define the start date and end date of their holiday, with the condition that the end date must be equal to or greater than the start date. Here is my current implementat ...

I am unable to utilize the map function as it results in a TypeError: The property 'map' is undefined and cannot be read

I recently delved into the world of "REACT" in order to work on the front-end of my own project. I encountered a problem for 2 days with the map function while getting data from my back-end and saving the IDs in the Cuartos array. I couldn't figure ou ...