Change the object's property names from camel case to sentence case

Consider an array of objects like this:

data = [{keyOne: 'value1', keyTwo: 'value2'},
          {keyOne: 'value3', keyTwo: 'value4'}];

We need to change it to look like this:

data = [{Key one: 'value1', Key two: 'value2'},
          {Key one: 'value3', Key two: 'value4'}];

To achieve this transformation, each property value should be converted from camel case to a sentence format, for example keyOne becomes Key one.

A function can be used for this conversion:

function convertToSentence(text) {
  const result = text.replace( /([A-Z])/g, " $1" );
  const finalResult = result.charAt(0).toUpperCase() + result.slice(1);
  return finalResult;
}

The challenge is applying this function to every object in the array. One way is to use data.forEach(item => ... );

Any suggestions on how to approach this task?

Answer №1

To iterate through an object, you can convert it into [key, value] pairs using the Object.entries() method, map through these pairs, and then convert them back to an object with Object.fromEntries().

I have developed a function called mapKeys that takes a transformFn as input and updates the keys of the object accordingly.

const mapKeys = (transormFn, obj) => Object.fromEntries(
  Object.entries(obj)
    .map(([key, value]) => [transormFn(key), value])
);

const myData = [{"firstName":"john","lastName":"y","hairColor":"black"},{"firstName":"mike","lastName":"x","hairColor":"green"},{"firstName":"alex","lastName":"z","hairColor":"brown"}];

function replaceIt(text) {
  const result = text.replace(/([A-Z])/g, " $1");
  const finalResult = result.charAt(0).toUpperCase() + result.slice(1).toLowerCase(); // result.slice(1).toLowerCase() should get you the desired form
  return finalResult;
}

const result = myData.map(o => mapKeys(replaceIt, o));

console.log(result);

An interesting suggestion by @ScottSauyet is to curry the mapKeys function. This eliminates the need for an arrow function when mapping through the array:

const mapKeys = transormFn => obj => Object.fromEntries(
  Object.entries(obj)
    .map(([key, value]) => [transormFn(key), value])
);

const myData = [{"firstName":"john","lastName":"y","hairColor":"black"},{"firstName":"mike","lastName":"x","hairColor":"green"},{"firstName":"alex","lastName":"z","hairColor":"brown"}];

function replaceIt(text) {
  const result = text.replace(/([A-Z])/g, " $1");
  const finalResult = result.charAt(0).toUpperCase() + result.slice(1).toLowerCase(); // result.slice(1).toLowerCase() should get you the desired form
  return finalResult;
}

const result = myData.map(mapKeys(replaceIt));

console.log(result);

Answer №2

Use Array.reduce along with Object.entries:

const transformedData = myData.map(
  obj => Object.entries(obj)
    .reduce( (accumulator, [key, value]) => ({
      ...accumulator,
      [modifyKey(key)]: value,
    }), {})
);

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

There was an issue encountered when trying to call a PHP file within an HTML table using Ajax and data.html

For a small project, I have various news items that need to be included from the "news_all.php" file into table data within the "dashboard.php" file. Due to the predefined root structure restrictions, using include('news.php') is not an option. I ...

Modify the javascript addEventListener to use 'scroll' instead of 'wheel'

I am currently attempting to modify this javascript event to trigger on scroll instead of the mouse wheel. I have attempted to make the following changes: window.addEventListener('wheel',function (e) changed to window.addEventListener('sc ...

Is it possible for Yarn to fail to include both ESM and CJS versions of a package during publishing or adding?

Our application is equipped with Parcel and utilizes a UI library consisting of react components. This UI library is built with Rollup and is privately published on NPM. I've been attempting to transition our application to Parcel 2, but I'm fac ...

Tips for creating animated card designs with HTML, CSS, and JavaScript

As I delve into the realm of CSS animation, my primary focus is on replicating the captivating card shuffling animation showcased at Here's a glimpse of the progress I've made so far: https://youtu.be/GDIJ2K22cnY While I've successfully im ...

Creating a functional hyperlink within a ui-sref element in Ionic

I'm struggling with a simple code snippet in Ionic 1. It basically shows a list of items that are clickable to navigate to a details page. However, I want to add functionality so that when clicking on the phone icon next to each item, it will initiate ...

An error occurred during conversion: trying to convert an object to an array

After reading numerous articles about this issue and trying multiple solutions, I am still unable to resolve it! I have been stuck with this error for the past 3 days and I'm hoping someone can assist me. Thank you in advance for any help! My situati ...

Invoke a function from within an event handler

Is there a way to trigger a function once an event has been completed? For example - $('.class').slideUp('fast', function() { // execute the function }); ...

Fixing perspective clipping in Three.js

In my Three.js project, I have a plane inside a sphere that I am applying a shader to in order to achieve certain visual effects on the sphere. To ensure that the plane is always facing the camera, I am using the lookAt method. However, I have noticed that ...

Verifying if checkboxes are selected in PHP using JavaScript

echo '<div class="col-lg-10 col-lg-offset-1 panel">' . "<table id='data' class='table'> <tr> <th></th> <th>Document No</th> <th>AWB NO</th> ...

Observing rxjs Observable - loop through the results and exit when a certain condition is met / encountering an issue with reading property 'subscribe' of an undefined value

I'm fairly new to working with rxjs and I've been struggling to find the right operator for what I want to achieve. Here's my scenario - I have an array that needs to be populated with results from another observable. Once this array has en ...

Reading data from a file and storing it in an array

Currently attempting to read data from a txt file and showcase the results in a message box. My plan involves extracting lines of 1000 and removing them from the array at a later stage in the code. At this point, I simply want to confirm that the file can ...

What is the best way to incorporate correct reference logic when utilizing Joi validation?

I am currently working on designing a straightforward schema to validate inputted number ranges. The condition is that the start value should be less than the end value, and conversely, the end value must be greater than the start value. Below is the sche ...

Enhancing WordPress Menu Items with the 'data-hover' Attribute

Looking for a solution to add "data-hover" to menu items on Wordpress, like: Wanting to insert: data-hover="ABOUT US" into <a href="#">ABOUT US</a> without manually editing the link's HTML to make it: <a href="#" data-hover="ABOU ...

How can we efficiently generate ReactJS Router for Links and seamlessly display a unique page for each Link?

Currently, I have an array of objects named titleUrl, which contains titles and URLs retrieved from an API. To display these as links on the sidebar, I am utilizing a custom component called MenuLink. The links are generated by iterating over the keys in t ...

Leverage the https module within your React Native application

How can I integrate the https standard library module from Node.js into a React Native project? Specifically, I need to use https.Agent for axios. Is there a recommended approach for achieving this integration? ...

Tips on sorting objects by comparing them to array elements

I have an array called myarrays and an object named obj. I need to filter the object by comparing the elements of the array with the keys of the object. If you want to see the code in action, you can check it out on StackBlitz: https://stackblitz.com/edit ...

Interacting with JSON API data in real-time using AJAX and the power of JQuery

I'm currently working on displaying data dynamically from an API, and everything is functioning well except for the "Next" and "Previous" links. I can't seem to get them to update the value count in the search bar. My problem lies in executing my ...

Continuously iterate through a PHP page until the session variable reaches a specific value

I am in the process of creating a web-based exam. All questions and answers are stored in a MySQL database. I began by retrieving and displaying one question along with multiple-choice answers. I used a session variable $_SESSION['questionno'] = ...

Sending a string to the server-side using Jquery Ajax

Is there a way to send variable data to the server side? I am looking for a solution. $("form").submit(function () { GetSelectedValues(); }); function GetSelectedValues() { var data = $("#DDL_WorkCategory").val(); } This ...

Exploring the capabilities of Set() and the for..in loop in JavaScript

function removeDuplicates(menuArray) { let flatmenus = menuArray.flat();//This method combines child and parent arrays into one unique array let combinedMenu = new Set();//Creates an object that removes duplicate elements flatmenus.forEach(dish => ...