Update the key names in an array of objects using the value from the first element of the array

I am working with raw json data extracted from a .csv file:

[{
    "A": "CustomerCode",
    "B": "Country",
    "C": "CountryCode"
},
{
    "A": "C101",
    "B": "AUS",
    "C": "AUS01",
},
{
    "A": "C102",
    "B": "AUS",
    "C": "AUS02",
}]

Is there a way to remove the first element of the array and change the key names in each object within the array like this:

[{
    "CustomerCode": "C101",
    "Country": "AUS",
    "CountryCode": "AUS01",
},
{
    "CustomerCode": "C102",
    "Country": "AUS",
    "CountryCode": "AUS02",
}]

Answer №1

To create new objects with keys from the first object in your array, you can utilize .map() in combination with Object.entries() and Object.fromEntries(). Here's how:

const arr = [{A:"CustomerCode",B:"Country",C:"CountryCode"},{A:"C101",B:"AUS",C:"AUS01"},{A:"C102",B:"AUS",C:"AUS02"}];

const prop_map = arr.shift();
const res = arr.map(o => 
  Object.fromEntries(
    Object.entries(o).map(([k, v]) => [prop_map[k], v]))
);

console.log(res);

In this code snippet, .shift() retrieves the first object from the array as a reference mapping object. The .map() function then processes each object in the array to create a new modified object. This modification is determined by what the inner function of .map() returns. Essentially, it converts the entries (key-value pair arrays [[key, value]]) of objects using another .map() method. Each key-value pair array is mapped to a new one where the key is defined by its associated value in the prop_map. Finally, Object.fromEntries() transforms this key-value pair array into an object, which becomes the final result generated by the .map() applied to the original array.

Please be aware that Object.fromEntries() may have limited browser compatibility, but a polyfill can be used if necessary.

Answer №2

To manipulate the array, start by removing the first element and then proceed to map over its contents.

let information = [{
    "A": "CustomerID",
    "B": "Region",
    "C": "RegionCode"
},
{
    "A": "ID101",
    "B": "USA",
    "C": "US01",
},
{
    "A": "ID102",
    "B": "USA",
    "C": "US02",
}];

// Eliminate the initial item in the array
information.shift();

let newInformation = information.map(({A, B, C}) => ({
    CustomerID: A,
    Region: B,
    RegionCode: C
}));

console.log(newInformation);

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

Using Cheerio with a Node.js bot

I am currently utilizing Cheerio to extract information from web pages in my .js files. However, I would like these files to automatically restart every 1 day to check for any new data. Instead of using setTimeout, which may not be efficient for managing ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

What could be the reason behind the varying outcomes browsers provide for the JavaScript expression new Date(-105998400000)?

When I use ASP.NET MVC 3 with the default Json serializer, I notice that dates from my JsonResults come back in the format /Date(-105998400000)/. To handle this, I extract the number and create a new Date object with this value. However, I am experiencing ...

What is the correct method for completely eliminating a mesh from the three.js scene?

I am looking for a way to fully remove meshes from a three.js scene without causing any memory leaks. I have noticed that reloading the same models multiple times can lead to browser crashes, indicating that memory is not being properly deallocated. ...

Using jQuery to clear a textarea when a select input is changed

Currently, I am in the process of developing a small text editor that enables users to edit files and create new ones. Here is how I have set up my select menu. <select name="reportname" id="reportname" class="form-control"> <option value="zr ...

The PHP function outputs the message: "Caution: Converting an array to a string in"

Within my PHP function below, I am attempting to explode an array and use a foreach loop to collect the data. Despite my efforts, I keep encountering the error mentioned in the subject. function getSwipableUsers() { $expInt = explode(',', $f[&a ...

Display or hide object fields in Java based on REST requests

Is there a way to configure the Item class so that specific fields can be shown or hidden depending on the REST call being made? For instance, I would like to hide colorId (and show categoryId) from the User class when calling the XmlController and vice ...

What are the steps for integrating mongoDB with an angular2 application?

I currently have my angular2 & mongoDB setup successfully. While I've managed to read JSON files using the HTTP service, my goal is to create a fully functional application with database connectivity as well. I'm seeking advice on how to con ...

executing ajax request to call a function, encountering partial success and encountering partial failure

Apologies for the lack of clarity in the title. I currently have a search engine that utilizes an ajax function. At present, when I type "t" in the search box, only the tags containing the word "t" are displayed (for example, if I type "t", then "test" sho ...

Image Handpicked by JCrop User

Successfully implemented JCrop example code for selecting an area on an image with a preview and getting coordinates. However, the challenge lies in allowing users to select an image from their file system, display it in the browser, and perform the afore ...

Guide on removing query parameters post a redirect using NextJS

Is there a way in NextJS to redirect a URL like /page?foo=bar to /page/bar? I checked out the documentation at https://nextjs.org/docs/api-reference/next.config.js/redirects but couldn't find a solution. This is what I have tried so far: { source: ...

Is it appropriate to utilize response headers (specifically 400 error codes) to communicate errors, especially when working with x-editable?

Exploring the capabilities of the plugin reveals that it offers two distinct callbacks upon posting a result: error and success. The error callback is triggered in cases where the server does not respond with a 200 header. This means that if the server d ...

Derive Schema from deeply nested JSON string column using Pyspark

Given the table provided below: body {"Day":1,"vals":[{"id":"1", "val":"3"}, {"id":"2", "val":"4"}]} The objective is to define the schema in Pyspa ...

Manipulate the visibility of a child element's dom-if based on a property retrieved from the parent element

Exploring the world of Polymer, I am eager to tackle the following scenario... I have a binding variable called {{readonly}} that sends data from a parent Dom-HTML to a child Dom-HTML in my Polymer project. The code excerpt looks something like this... C ...

How to Handle Missing Data in Swift4 Using URLSession and JSONDecode

Utilizing Swift4, iOS11.1, Xcode9.1, The parseData method provided below appears to be functioning almost as expected. The URLSession and JSONDecode successfully fetch a correct JSON-data set. However, it is perplexing that when using a normal Browser, a ...

Verification of user input field

For this mini deposit app, I needed to implement validation for the input field to check for three different conditions: no blank entries, only numerical values, and no negative numbers. Despite having the functionality, my attempts at implementing validat ...

Using the AJAX post method to generate a JSON object from database results and send it back to a jQuery UI Dialog

I wrote a script that loads sample images from the database based on the relevant category when the page loads. Here's a simplified version of the PHP script: <?php $category = 'granite'; $samples = 'SELECT * FROM material WHERE ma ...

Tool to track character limits in multiple text fields

I'm facing a challenge with a form that includes 3 text areas, a copy button, and a reset button. My goal is to concatenate all the characters in the text areas to get a sum which will be displayed next to the copy/reset button. The character limit is ...

What could be causing bundle.js to remain in a pending status on my website?

Whenever I try to open a page from my project, the browser keeps showing loading forever and in the network tab, the status of bundle.js is pending. (Interestingly, if I open other routes of the project, everything works fine). If I remove all product var ...

Keep an ear out for updates on object changes in Angular

One of my challenges involves a form that directly updates an object in the following manner: component.html <input type="text" [(ngModel)]="user.name" /> <input type="text" [(ngModel)]="user.surname" /> <input type="text" [(ngModel)]="use ...