What is the best way to eliminate a specific character from the key of an array of objects using JavaScript?

My JavaScript object looks like this:

result = [
   {"Account_ID__r.Name":"Yahoo Inc Taiwan","Contact_ID__r.Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42283427302c2d2e2602362a27313623306c212d2f">[email protected]</a>"},
   {"Account_ID__r.Name":"WXIA-TV","Contact_ID__r.Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6ccd1c9c9cac4d4cfc1ced2e69797c388c5c9cb">[email protected]</a>"}
]

I'm looking to modify the keys in the object by removing periods, for example changing Account_ID__r.Name to Account_ID__rName.

The updated array should look like this:

result = [
   {"Account_ID__rName":"Yahoo Inc Taiwan","Contact_ID__rEmail":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c9d5c6d1cdcccfc7e3d7cbc6d0d7c2d18dc0ccce">[email protected]</a>"},
   {"Account_ID__rName":"WXIA-TV","Contact_ID__rEmail":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472d3028282b25352e202f33077676226924282a">[email protected]</a>"}
]

I attempted to create a new array using a

for (var key of Object.keys(result)) { }
loop, but it was unsuccessful.

This is the code I tried:

result.forEach(item => {
                    for (var key of Object.keys(item)) {
                        var keyWithoutPeriod = key.replace(/\./g,'');
                        this.datatableData.push({
                            [keyWithoutPeriod]: item[key] 
                        });
                    }
                });

The resulting datatable looks like this:

datatable = [
   {"Account_ID__rName":"Yahoo Inc Taiwan"},{"Contact_ID__rEmail":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="117b6774637f7e7d7551657974626570633f727e7c">[email protected]</a>"},
   {"Account_ID__rName":"WXIA-TV"},{"Contact_ID__rEmail":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a607d6565666878636d627e4a3b3b6f24696567">[email protected]</a>"}
]

This structure is not what I require. Any assistance would be greatly appreciated. Thank you! 😃

Answer â„–1

You have the opportunity to extract data entries, eliminate any unwanted characters, and create new objects.

const
    data = [
        { "Account_ID__r.Name": "Yahoo Inc Taiwan", "Contact_ID__r.Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="402a3625322e2f2c2400342825333421326e232f2d">[email protected]</a>" },
        { "Account_ID__r.Name": "WXIA-TV", "Contact_ID__r.Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68021f0707040a1a010f001c2859590d460b0705">[email protected]</a>" }
    ],
    result = data.map(obj => Object.fromEntries(Object.entries(obj).map(([key, value]) => [key.replace(/\./, ''), value])));

console.log(result);

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

Pattern matching without any specific order in a PostgreSQL array field, with the ability to use 'OR' for conditions

Summary I am currently developing a data analysis tool that interacts with a PostgreSQL database and is capable of constructing SQL queries to filter rows based on user input. Each row in the database represents a record containing input data and correspo ...

The post feature is not delivering the object as expected

I have created a Login page that is supposed to post Username and Password using Axios. I wrapped the username and password into an object as shown in the code below, but when I submit the form, I receive a "201" response. Everything seems to be working fi ...

Ways to expand the play and pause buttons and adjust the height of an HTML audio player

It's clear that the PLAY/PAUSE icons are smaller than intended, and the entire player is thinner than desired, making it difficult for some viewers to see. How can I enlarge the entire player? I have read that we do not have access to individual contr ...

How can you create an animation that plays forward on the first click and then reverses on the second

After coming across numerous similar questions, I realize that most of them refer to the outdated .toggle() function. My main challenge lies in achieving the desired effect where div#p moves right on the first click and then returns to its original positio ...

Adjust the horizontal position of the background by +/- X pixels

Is there a way to adjust the background-position by a specific distance, say 20px, from its original position? For example: $(".selector").animate("slow").css("backgroundPosition", "center -=20px"); (Unfortunately, this approach doesn't yield the d ...

Extracting and transforming an array into a list with the desired outcome

Looking for a way to flatten the array below into a single line array using Typescript/JavaScript? Student: any = [ { "id": "1", "name": "Jhon", "Marks": { "Math": "90", "English": "80", "Science": "70" } }, { "id": "2", "name": "Peter", "Marks": { "M ...

Why aren't variables showing up on the right when using writeFileSync in Node.js?

I'm attempting to insert a variable as ${Y} but instead of getting the actual data in Y, my output is showing (how can I write variable ${Y}). Does anyone have a solution for this? const fs = require('fs'); const Y = fs.readFileSync('./ ...

Use JavaScript to load and set a background image for a div

When it comes to loading different images onto an "img" tag by printing their URLs using JavaScript and then letting CSS manipulate the content in the tag, I have a code snippet that does just that. $(window).load(function() { var randomImages = [&apo ...

What is the process for performing a redirection in Node JS?

I have been working on a task to redirect a page to the home page with the route '/search' upon form submission. Within my submit.html file, there is a form that utilizes the '/submit' post method to submit the form data when the submit ...

The functionality of Styles in Material UI seems to be malfunctioning

I'm currently learning how to use Material UI for React, specifically focusing on makeStyles. Below is the JavaScript code I have: import React from "react"; import MenuIcon from "@material-ui/icons/Menu"; import EventNoteIcon fr ...

Getting a portion of a href link in Java using Selenium

I am looking to compare the current URL in Google Chrome with a specific href link that contains two URLs. I need to extract the first link from this specific href link: click here <a href="http://pubcontentqa.perion.com/dz2/html/interstitial.html?http ...

Having trouble showing the text on the screen, but after checking my console, I notice empty divs with p tags. Surprisingly, the app is still functioning properly without any

Currently, I am developing a joke app entirely on my own without any tutorials. One of the components in the app is SportsJokesApi, which retrieves data from a local json folder (SportsJokesData) that I have created. Here is how it is structured: const Sp ...

Is there a way to retrieve two separate route details using jQuery simultaneously?

Clicking the checkbox should display the Full Name: input type="text" id="demonum" size="05"> <button type="button" onclick="load_doc()">click</button><br><br> <input type="checkbox" id ="check" > The r ...

What are some ways I can integrate my Json object into my IONIC app rather than relying on a hardcoded object?

I stumbled upon this IONIC app's services.js file and found an example using a hardcoded object called "employees." Instead of using the hardcoded object, I wanted to use a JSON file. However, my attempt to make this change did not work as expected. I ...

JavaScript WYSIWYG Algorithm

Despite my searches on SO, it appears that most questions revolve around simply making a div editable using contenteditable="true". I am interested in finding the most effective method for tracking all formatting tags applied to a document. Merely togglin ...

Incorporate Add to Homescreen functionality into your Angular 4 Project using JavaScript

Currently I am in the beginning stages of learning Angular development. One of my assignments involves integrating the add to homescreen jQuery plugin into one of my pages. This is my attempt at implementing it in my home.component.ts file: ngAfterViewIn ...

Json File in a Jar Format

Even though I have added the necessary imports to my code, I am still encountering an error with the line: JsonObject obj = new JsonParser().parse(input).getAsJsonObject(); The error message reads: "JsonObject cannot be resolved for a type." import org. ...

Encountering an error while attempting to remove a duplicated element from an array

When the program reaches the removeIf() function, it encounters an error and fails to produce any output, behaving as though there is a language-related issue. It would be helpful if you could maintain the same code logic. public static SalmonSumario[] f ...

Creating a fresh JSON structure by utilizing an established one

I have a JSON data that contains sections and rubrics, but I only need the items for a new listing. The new object named 'items' should consist of an array of all the items. The final JSON output should be sorted by the attribute 'name&apos ...

Using Javascript to parse a regular expression in a string

I am facing a challenge with a JavaScript string that contains contact information that needs to be filtered. For example, I want to mask any email or phone number in the message. I have attempted the following approach: function(filterMessage) { ...