How to extract a property name from an object in JavaScript without using quotation

I currently have an object that resembles the following:

const obj = {
  id: 1,
  name: {
    "english-us": "John",
    "english-uk": "John",
    "italian-eu": "Giovanni",
  },
};

My goal is to convert all property names that are strings into non-string ones, like so:

const obj = {
  id: 1,
  name: {
    english_us: "John",
    english_uk: "John",
    italian_eu: "Giovanni",
  },
};

It's worth noting that I'm unable to alter the original object as it comes from an axios request.

Answer №1

To manipulate the data in JavaScript, you can utilize regular expressions (regex) along with the stringify method.

let output = JSON.parse(JSON.stringify(obj).replace(/"(.*?)":.*?,?/g,
                                       key=>key.replace(/\-/g, `_`)));

The resulting Output will be:

console.log(JSON.stringify(output, null, 4));
/*
{
    "id": 1,
    "name": {
        "english_us": "John",
        "english_uk": "John",
        "italian_eu": "Giovanni"
    }
}*/

Answer №2

Looking to duplicate the item? Consider exploring this answer that provides guidance on defining the attributes: click here

Answer №3

There are multiple approaches to achieve this task. In the following example, a function is used to convert keys during each iteration of the name entries. The properties are then added to a new object called names, which is eventually merged into a new object along with the existing properties of the original object.

const obj = {
  id: 1,
  name: {
    "english-us": "John",
    "english-uk": "John",
    "italian-eu": "Giovanni",
  },
};

const convert = (key) => key.replace('-', '_');

const updatedName = {};

for (const [key, value] of Object.entries(obj.name)) {
  updatedName[convert(key)] = value;
}

const newObj = { ...obj, name: updatedName };

console.log(newObj);

Answer №4

One way to manipulate data is by converting objects to JSON and then back again.

const obj = {
  id: 2,
  name: {
    "english-us": "Alice",
    "english-uk": "Alice",
    "italian-eu": "Alicia",
  },
};
console.log(JSON.parse(JSON.stringify(obj)))

Answer №5

Here are two methods to duplicate an object and change all keys within its name property:

const obj = {
  id: 1,
  name: {
    "english-us": "John",
    "english-uk": "John",
    "italian-eu": "Giovanni",
  },
};
// Make a copy of obj
const myObj = window.structuredClone ?
  structuredClone(obj) : JSON.parse(JSON.stringify(obj));

// Modify the keys in myObj.name
Object.keys(myObj.name).forEach(key => {
  myObj.name[key.replace(/\-/g, `_`)] = myObj.name[key];
  delete myObj.name[key];
});

console.log(myObj.name.english_us);
// The original obj remains unchanged
console.log(obj.name[`english-us`]);
// The key myObj.name[`english-us`] does not exist
console.log(myObj.name[`english-us`]);

// Another approach: clone and rename in a single step
const myObjClone = {
  ...obj,
  name: Object.fromEntries(
          Object.entries(obj.name)
            .reduce( (acc, [k, v]) => 
              [ ...acc, [ k.replace(/\-/g, `_`), v ] ] , [] ) )
};
console.log(myObjClone.name.italian_eu);
// The original obj is unaffected
console.log(obj.name[`italian-eu`]);
// The key myObjClone.name[`italian-eu`] does not exist
console.log(myObjClone.name[`italian-eu`]);

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

The specified file for import cannot be located or is unable to be read: node_modules/bootstrap/scss/functions

I am currently using core UI version 2.1.1 along with react. Upon attempting to execute npm start, I encountered the following error: (/Users/umairsaleem/Desktop/abc/abc/node_modules/css-loader??ref--6-oneOf-5-1!/Users/umairsaleem/Desktop/abc/abc/node_mo ...

Using componentDidUpdate to create a loop

Within the App Component, I am sending a self-invoking function to the getBgColor function in the WeatherForecast Component. This function retrieves a value from the child component WeatherForecast and transfers it back into the App Component to update the ...

Error handling proves futile as Ajax upload continues to fail

Utilizing a frontend jQuery AJAX script, I am able to successfully transfer images onto a PHP backend script hosted by a Slim framework app. However, there is one specific image (attached) that is causing an issue. When the backend attempts to send back a ...

How to style a date and time object using angularjs

What is the best way to convert a PHP datetime object to the format "May-27-1990"? ...

Having trouble with getting Express to automatically redirect to the main page upon user login

Currently, I am working on setting up a user login section. Despite the user_router successfully sending a JSON response, I am facing an issue with getting Express to send a new HTML page back to the client. The initial page offered is login.html, which co ...

I'm working on updating a field within a Firestore document using ReactJS

I am encountering an issue while attempting to update a field within a document in Firestore using ReactJS. Interestingly, others have successfully done it without any errors. app.js const app = initializeApp(firebaseConfig); const auth = getAuth(app); co ...

The video continues playing even after closing the modal box

I am facing an issue with my code where a video continues to play in the background even after I close the modal. Here is the code snippet: <div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria- ...

The function fails to return a true value

Why is true never returned even when the given name exists in the array rows and the if(rows[i].userName == name) condition is met? function checkIfUserExists(name){ var isUserExists = false; OOTW.MYSQL.query('SELECT * FROM Time',functio ...

Apply a jQuery class to six randomly selected elements that share the same class attribute

I have a total of 12 elements that all have the "block" class, and I am looking to randomly assign the "active" class to exactly 6 out of the 12 elements. My initial thought was to use a for loop to achieve this task, but I'm unsure about how to go a ...

Ensure that everything within the Container is not see-through

Fiddle:https://jsfiddle.net/jzhang172/b09pbs4v/ I am attempting to create a unique scrolling effect where any content within the bordered container becomes fully opaque (opacity: 1) as the user scrolls. It would be great if there could also be a smooth tr ...

There are no documents found with the specified UUID in MongoDB

I have been attempting to retrieve a specific document from MongoDB that includes the field "ownerId" containing a binary UUID. In the Mongo console, when I run the command db.dataset.find({ownerId: BinData(3,"ZQ6EAOKbQdSnFkRmVUUAAA==")}).pretty() The ou ...

I keep encountering an issue in my application where I am receiving an error stating that

Encountering the error $ is not defined in my application due to the usage of the npm package. Link to the npm package Attached is the code snippet: Link to the code sandbox import React from "react"; import "./styles.css"; import { ZoomMtg } from "@zoo ...

Create a PHP array containing strings and generate two-dimensional arrays as a result

One issue I encountered in PHP involves creating an array with a string while also cutting some images. Within my code, buildProject.php is included in index.php (with session_start(); for _session at the top). buildProject.php <?php $list_project = ...

What is the technique for retrieving the data-id value and transferring it to a different page with jQuery's post method?

Here is the code I'm working on: <a href="#view_contact" class="btn btn-info btn-xs view" data-id="<=$row['ADMINISTRATOR_ID'];?>" data-toggle="modal">View</a> I'm trying to fetch the value of data-id and pass it to a ...

Stop the Form from Submitting When Errors are Present

In the midst of explaining my issue, I must first share details about a form I'm developing. It's a Registration form where upon submission by clicking Submit, users won't immediately reach a Successfully Registered page. Instead, they' ...

Error message: React is unable to locate the map container in the Leaflet library during rendering

I am working with a custom React and Leaflet.js component... export const CustomMapSetLocationComponent = (props) => { React.useEffect(() => { let marker = null let map = null var container = L.DomUtil.get('setLocationMap') ...

A guide on using Selenium to interact with a doughnut pie chart element

I am having difficulty performing a click event on the colored ring part of this doughnut pie chart. Currently, I can locate the element for each section of the chart, but the click event is being triggered in the center of the chart (empty inner circle) w ...

On page load, refresh the content of the div based on the selected radio button values

My goal is to automatically collect the values of checked radio buttons when the page loads, rather than waiting for a user interaction like clicking a radio button. Below is the JavaScript code I am using: $(function () { updateDivResult(); $(&a ...

The error message "Property 'destroy' of undefined cannot be read in DataTables"

I need to develop a function that can create a new DataTable. If there is an existing table, I want the function to first destroy it and then create the new one. This is what I have so far: $.ajax().done(function(response){ Init_DT(response[& ...

Integrate with GraphQL API using Express.js

I am facing an issue with connecting to an external API (GraphQL) on Express.js. Can anyone recommend some good tutorials on this topic? Additionally, I encountered the following error: Error message link - image Is it feasible to establish a connection ...