What is the best way to update properties of an array object using a map in pure JavaScript for maximum efficiency?

Looking for an efficient solution to replace property keys in an array of objects using a map? Here's an example scenario:

// Consider an array of objects:
var records = [
  {"Id": "0035w000036m j7oAAA", "Business Phone": "(212) 842-5501"},
  {"Id": "0035w000036mj7oXXX", "Business Phone": "(212) 842-7777"}
];

// Map for property key replacement:
var colHeaderToFieldApiName = {"Business Phone": "Phone"};

// Expected output:
var result = [
  {"Id": "0035w000036mj7oAAA", "Phone": "(212) 842-5501"},
  {"Id": "0035w000036mj7oXXX", "Phone": "(212) 842-7777"}
];

I've written a solution that functions correctly, but I'm open to suggestions for improvement. Here's what it currently looks like:

records.forEach(function(obj) {
  for (const prop in obj) {
     if (Object.prototype.hasOwnProperty.call(obj, prop)) {
       const fieldApiName = colHeaderToFieldApiName[prop];
       if (fieldApiName) {
         obj[fieldApiName] = obj[prop];
         delete obj[prop];
       }
     }
   }
});

Answer №1

Within this example, the keys found in newKeys will be utilized to substitute the existing keys within the input array:

var records = [
  {"Id": "0035w000036m j7oAAA", "Business Phone": "(212) 842-5501"},
  {"Id": "0035w000036mj7oXXX", "Business Phone": "(212) 842-7777"}
];

// Define the key replacements:
var newKeys = {"Business Phone": "Phone"};

// Expected outcome:
var result = records.map(o=>
 Object.fromEntries( Object.entries(o).map(([k,v])=> [newKeys[k]??k,v] ) )
);
console.log(result);

/* Output
[
  {"Id": "0035w000036mj7oAAA", "Phone": "(212) 842-5501"},
  {"Id": "0035w000036mj7oXXX", "Phone": "(212) 842-7777"}
];
*/

The process of replacing keys is dependent on the newKeys object: exclusively the keys defined in that object will undergo replacement with their new counterparts, while all other keys will remain as they are.

Answer №2

In my previous experience, this is the approach I have taken.

While it may not be the most efficient method, it becomes relevant when dealing with a large volume of key remapping.

Some developers may find this approach less intuitive, but personally, I find it quite clear and effective, so I am sharing it here.

The process involves:

  • Creating a key replacement function that is curried, as I prefer this style of function composition.

  • Iterating through the list of objects using a map function and applying the key replacement function.

Here is the implementation:

const replacekeys = km => o => Object.fromEntries(
  Object.entries(o).map(([k, v]) => [k in km ? km[k] : k, v]))

Implementation example:

records.map(replacekeys(colHeaderToFieldApiName))

Additional notes:

  • You can use o.hasOwnProperty(k) if you want to avoid prototype chain lookup when checking for key existence;
  • If you prefer a different functional style than currying, you can modify the function to
    replacekeys = ([km, o]) => ...
    and use it as
    records.map(o => replacekeys(colHeaderToFieldApiName, o))

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

Choose all the checkboxes that use Knockout JS

Struggling with implementing a "select all" checkbox feature as a Junior developer on a complex project utilizing knockout.Js and Typescript. I can't seem to figure out how to select all existing checkboxes. Here is the HTML: <td> <inp ...

Retrieve the parameter values in PHP that were passed from AngularJS

This is my first time working with PHP and AngularJS. I am trying to pass parameters from AngularJS to a PHP file, where they will be used in an INSERT query. I have set up an XMLHttpRequest to call the PHP file (addsubscriber.php?par1=val1&par2=val2) ...

When trying to access the key value of a dynamically generated object, it returns as undefined

I am facing a challenge with my student object structure... { Freshmen: [{id: 3}, {id: 5}], Sophomores: [{id: 2}, {id: 6}], Juniors: [{id: 1}, {id: 8}], Seniors: [{id: 9}, {id: 4}, {id: 7}] } My goal is to retrieve full student objects from the d ...

What is the best way to deselect all "md-checkboxes" (not actual checkboxes) on an HTML page using a Greasemonkey script?

After spending a frustrating amount of time trying to disable the annoying "md-checkboxes" on a certain food store website, despite unchecking them multiple times and reporting the issue without any luck, I have come to seek assistance from knowledgeable e ...

Ensure that the flex item spans the entire width of the page

I'm struggling to make my audio-player resize properly to fit the full width of my page. I can't seem to figure out what I'm missing or doing wrong... (Current Look) https://i.sstatic.net/tEtqA.png I'm attempting to utilize HTML cust ...

Arrow function returns itself, not the function

While working with React, I've been using utility functions for managing API calls. I noticed that when the arrow function is no longer anonymous, it successfully returns a pending promise – which is exactly what I want. However, if the arrow functi ...

Guide to implementing CSS3 transitions with prefixes using JavaScript

Is there a way to apply CSS styles using JavaScript when I don't have access to the CSS file? #fade div { -webkit-transition: opacity 1s; -moz-transition: opacity 1s; -o-transition: opacity 1s; -ms-transition: opacity 1s; transition: ...

Utilizing Jquery functions within the AngularJS framework

Utilizing Uikit along with its pagination feature, I am attempting to implement this function for changing the page: $('[data-uk-pagination]').on('uk-select-page', function(e, pageIndex){ console.log("page " + pageIndex); ...

Ways to eliminate the absence of the 'Access-Control-Allow-Origin' header in an error message when using a Java-based web-service server

I'm currently working on developing a webservice using Java as the server and Javascript as the client. My goal is to send a Post request with JSON data and receive a Post response with JSON data from the server. However, since the client and server h ...

Adjusting the font color when hovering over multiline text

I am currently in the process of coding a website for my job, and I am working on changing the text color when it is hovered over. However, there seems to be a break in my code causing the text not to highlight all at once. Any guidance or suggestions on h ...

Tips for preventing breaks in typography

I have implemented a material ui Typography component, but it's causing a line break even though there is enough space. Here is the code snippet: <Box flexDirection="row"> <Typography> Gender: <RadioGroup row ...

The installation of npm modules is failing with the error message: "'react-scripts' is not recognized as a valid command, internally or externally."

As I revisited my old project on GitHub, things were running smoothly a few months prior. However, upon attempting to npm install, I noticed the presence of the node modules folder and encountered some npm errors. https://i.stack.imgur.com/awvjt.png Sub ...

Mastering the use of npm and sails to create HTML-PDF files effortlessly

UPDATE: I am simplifying my question and will address any other concerns in separate posts if necessary. The initial post was too lengthy, hoping for a straightforward guide on utilizing sails to its fullest potential. Apologies. To begin with, my knowled ...

What is the process of connecting JSON keys to one another?

I am currently brainstorming a solution to link two distinct JSON formats with their respective keys. Here are the two formats: { "price": [ 511, 499, 419, 312 ], "paid": "OK", "contract": "year", "begindate": "01/01/2018", " ...

JavaScript: a highly effective method for verifying if a variable is a function, an array, or an object

Imagine a scenario where we have a variable that could potentially be a function, object, or array. I am in search of the most efficient method to determine its type. In my opinion, the current approach is not optimized because if I already know that isF ...

What is the best way to create an index for a user-provided value in a textbox

Looking for guidance on how to set an index to user-provided values in a textbox, append them to a table in a new row, and display that index in the first column of every row. I am unfamiliar with this type of functionality. $(document).ready(function() ...

Divergent functionality of regular expressions in Internet Explorer and Chrome when handling white spaces

Here is a function that validates input by checking for numbers and no spaces in between: checkInputValidity: function() { var isValid = true; var idNumber = this.getView().byId("iDNumber"); var regex = /^[0-9]+$/; if (idN ...

Identify and react to an unexpected termination of an ajax upload process

My ajax uploading code can determine if a file was successfully uploaded only after the upload has completed. If the upload is terminated before completion, no data is returned. Is there a way to detect when an upload is unexpectedly terminated and alert t ...

Navigating JSON data with unexpected fields in Typescript and React.js

Looking to parse a JSON string with random fields in Typescript, without prior knowledge of the field types. I want to convert the JSON string into an object with default field types, such as strings. The current parsing method is: let values = JSON.parse ...

When passing req.body to another file for processing, it is displaying as undefined in node.js

Currently tackling an issue with a project involving nodejs where the request body is showing up as undefined Fetching some data on the client side, but encountering difficulties Received an error pointing out that the property is either undefined or nul ...