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

Update individual component based on selected value

I am working on a blogs page that consists of two main components: filter and card <template> <div> <div v-if='$apollo.loading'>Fetching data...</div> <div v-else> <FilterComponent :categorie ...

What is the best way to instruct firebase-admin to halt during test execution?

Running process.exit() or --exit in my mocha tests doesn't feel right. I'm currently working on code that utilizes firebase-admin and while attempting to run mocha tests, wtfnode showed me: wtfnode node_modules/.bin/_mocha --compilers coffee:co ...

Setting an Alias for AVA Tests: A Step-by-Step Guide

I need to set up global aliases in my project without using Webpack or Babel. Currently, I am testing with AVA. The npm package module-alias allows me to define aliases in my package.json file. However, when I try to create a basic example following the d ...

What is the best way to insert a Button within a Tab while ensuring that the indicator remains in the appropriate tab?

Is it possible to include a button inside a Tab? When I click on "Homepage", the tab switches correctly with the indicator showing on the right tab. However, when I click on "Profile", the indicator moves to the logout button instead. How can I fix this ...

Unable to retrieve image

I want to save a Discord user's profile picture on Replit, but even though it downloads successfully, the image is not displaying. Here is the code I am using: const request = require('request') const fs = require('fs') app.get(&qu ...

Experiencing difficulty incorporating JSON and JS into jQueryhandleRequestJSON and JS integration with jQuery

I'm having trouble fetching the 'sigla' field from a JSON file and inserting it into an HTML 'option object'. I could use some assistance with this issue, so if anyone out there can lend a hand, it would be much appreciated! Here ...

Narrow down product selection by multiple categories

I'm currently in the process of working with Express and MongoDB, where I have data items structured like the following: { "_id": { "$oid": "63107332e573393f34cb4fc6" }, "title": "Eiffel tower&quo ...

Tips for replacing default arrow icons with 'Previous' and 'Next' buttons in a Material-UI pagination element

I've been struggling to find a solution with my code provided below. Despite multiple attempts, the issue remains unresolved. import React from "react"; import { gridPageCountSelector, gridPageSelector, gridPageSizeSelector, useGridA ...

Node server quickly sends a response to an asynchronous client request

Apologies for my lack of writing skills when I first wake up, let me make some revisions. I am utilizing expressjs with passportjs (local strategy) to handle my server and connect-busboy for file uploads. I believe passport will not have a role in this pr ...

Express middleware for serving static files using express.static() is not properly handling routing and is throwing an error stating that next()

During the development and testing phase on my local machine, everything was working as expected. However, once deployed to our UAT environment using Docker, I encountered some issues that are puzzling me: next() is not a function Another problem I'm ...

Error encountered in Ionic app: array.push() is not a valid function

A situation arose in my application where I have a controller and factory set up. Inside the factory, there is an array that should hold IDs of certain elements. However, when attempting to push an element into the array, an error is triggered stating: ...

Retrieving selected options from a jQuery mobile multiselect for database storage

I'm currently working on extracting values from a select list in a jQuery mobile application. Here's the markup for my select element: <div data-role="fieldcontain"> <label for="stuff" class="select">Stuff:</label ...

Decipher JSON arrays within arrays in Excel using a targeted method

After receiving some assistance, I was unsure whether to continue in the original post or create a new one for my query. Eventually, I decided to start a new question as it pertains to a different issue. Feedback on this decision is welcome for future refe ...

I encountered a challenge with a cross-site scripting filter that is preventing me from storing a JavaScript variable in a MySQL database using a

I am currently working on a project where I need to save a JavaScript variable into a MySQL database using a Python CGI script. In this case, the JavaScript variable contains the following information: <li style = "width: 300px; background-color: white ...

Obtain the specific key's value from a new Map state

In my code, I've defined a variable called checkedItems as a new Map(); When I try to console.log(checkedItem), the output is as follows: Map(3) {"1" => true, "1.5" => true, "2" => false} Is there a way for me to ...

Revamping this snippet - JavaScript with NodeJs

Currently working on a basic CRUD application, encountering an issue with obtaining the auto-incrementing value for the latest account in MongoDB. To provide more context, I've included the snippet below to achieve the following: 1) Conduct validati ...

Does aoMap function exclusively with THREE.BufferGeometry?

Can you provide guidance on setting up an aoMap for a standard THREE.Geometry object? Is there a demo available to reference? var uvCoordinates = geometry.attributes.uv.array; geometry.addAttribute('uv2', new THREE.BufferAttribute(uvCoordina ...

Comparing Encrypted Passwords with Bcrypt

Encountering an issue with comparing passwords despite accurately storing the hashed password during registration. Database - MongoDB Node.js version - v18.17.0 Bcrypt version - 5.1.1 Below is my userSchema: const userSchema = new mongoose.Schema({ u ...

Choosing a random element in React: A step-by-step guide

I'm currently working on a dynamic website that aims to load a random header component upon each refresh. Despite my various attempts, the functionality operates smoothly during the initial load but consistently throws this error on subsequent refresh ...

JavaScript code for initiating the npm start command

Is it possible to include the npm-start command in a JavaScript script? Requirement: Develop a JS script capable of triggering the npm-start command. Operating System: Microsoft Windows I need to turn it into a Windows service. However, in the code snip ...