What is the best way to change the name of a property within an object

I need to update the names of properties in a nested object.

  {
     0: {value: "can_view"},
     1: {value: "can_create"}
  }

The desired output should be:

  {
     user_can: "can_view",
     user_view: "can_create"
  }

Answer №1

To achieve this task, follow these steps:

  • Retrieve the entries using Object.entries()
  • Apply map() to it and substitute each key with the desired value
  • Transform it back to an object using Object.fromEntries()

const obj = {
  0: {value: "can_view"},
  1: {value: "can_create"}
}
const result = Object.fromEntries(Object.entries(obj).map(([key, val]) => [val.value, val.value]));
console.log(result)

Answer №2

Enhancing Maheer Ali's response. Here is the updated version:

const data = {
      0: {value: "can_view"},
      1: {value: "can_create"}
    }
    var result = Object.fromEntries(Object.entries(data).map(([key, value]) => [value.value.replace("can", "user"), value.value]));
    
    var myOutput = JSON.stringify(result).replace(/"(\w+)"\s*:/g, '$1:');
    console.log(myOutput);
    alert(myOutput)

OUTPUT:

  {
   user_view: "can_view",
   user_create: "can_create"
  }

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

Vue.js HTML5 Editor_vueful

I am currently utilizing browserify and attempting to incorporate the vue-html5-editor library from https://github.com/PeakTai/vue-html5-editor. However, when I attempt the following code: Vue.use(require('vue-html5-editor')); An error is thro ...

What is the best way to retrieve a value from the final element in a JSON document stored in MySQL?

I am currently working with MySQL version 8.0.18-commercial One of the columns in my MySQL query is returning a JSON Document. ServerName Status abc.com JSON Document(as shown below) The content of the Status column looks like this: { &quo ...

Can the reference to an array be obtained from the referent of its element?

I have a PHP function that takes an array as the first parameter and one of its keys as the second parameter. function fun(&$a, $k) { ...... } I am looking to update the function so that it only requires passing $a[$k] as a single parameter. Within t ...

Guide to parsing a JSON array enclosed in square brackets within curly braces

I'm having trouble retrieving the array data within square brackets inside curly braces. The JSON output is as follows: {"data":{"user":[{"transaction":"45455","date":"2013-10-28" }],"msg":"ok"},"error":[]} I attempted the following: $obj = json_de ...

What is the best way to avoid looping through duplicate keys in a JSON using Javascript?

I have been struggling to find a solution to a basic question on my own, despite my attempts. I apologize in advance for my inability to find the answer. The issue I am facing is with a JSON object that contains multiple keys with the same name, for examp ...

Protractor Throws Element Visibility Issue

When attempting to check a checkbox in the UI, I encounter an "ElementNotVisibleError: element not visible" error. Strangely, I am able to successfully capture and click the checkbox using the console in Chrome developer tools. Has anyone else experience ...

Sending an error from one asynchronous function to another

I have a complex system that utilizes async/await. My goal is to handle various types of errors from an async function within a single try/catch block. This function is called from another async function. Unfortunately, I've been unable to successfu ...

Krajee Bootstrap File Input, receiving AJAX success notification

I am currently utilizing the Krajee Bootstrap File Input plugin to facilitate an upload through an AJAX call. For more information on the AJAX section of the Krajee plugin, please visit: Krajee plugin AJAX The JavaScript and PHP (CodeIgniter) code snippe ...

Encounters a fault while processing the php output

Displaying an error in the query The browser is showing the correct answer. $.ajax({ type: "POST", url: url, async: true, contentType: " charset=utf-8", dataType: "XMLHttpRequest", success: func ...

The style from 'http://localhost:2000/cssFile/style.css' was rejected because its MIME type was 'text/html'

Currently, I am attempting to include my style.css file in the home.ejs file being rendered by express.js. However, I keep encountering the following error: Refused to apply style from 'http://localhost:2000/cssFile/style.css' because its MIME t ...

Adding a text field on top of a div based on the dropdown value selection

I am working with a dropdown option inside a div. I want to make it so that when the last option is selected, a text box will appear on top of the dropdown. And when a different option is selected, the text box should be disabled. How can I achieve this? ...

What is the best way to acquire the href value from this source?

Looking to extract the dynamic value "3 Sent" from the html snippet provided. How can this be achieved? <ul class="nav nav-tabs some-tabs"> <li class="active"> <a href="#accepted" data-toggle="tab">1 Accepted</ ...

Troubleshooting Knockout.JS: Why self.myObservable is not working and the importance of code organization

My webpage uses knockout to handle a search field, dropdown selection, and page number. These elements are all initialized with default values for the first run or when the page is accessed. I'm encountering an error that says: "self.selectedTeamId i ...

Utilizing AngularJS routes to load a specific URL when accessing a page for the first time

Working on developing a Single Page Application using AngularJS, my configuration settings appear as follows: app.config(["$routeProvider", function($routeProvider) { return $routeProvider .when("/", { redirectTo: " ...

"Counting Down with PHP and jQuery : A Dynamic

I recently received a tutorial on how to combine PHP date function with jQuery. I am looking to modify the script so that when a specific time is reached, it redirects to another page. I attempted to make the changes myself but encountered some issues. Y ...

Can you explain the functionality of the NextSibling method?

I have a question about how the property NextSibling behaves when using the method getElementsByClassName(). Let me illustrate the issue with this code example: function Sibling() { var x = document.getElementsByClassName('firstClass')[0]; ...

Managing browser navigation within a web application

I am currently developing a web-based application for internal use in the company I work for. The application is quite intricate, featuring numerous forms that will enable users to both view and input data, which will then be stored in a database upon savi ...

Angular UI directive for modal confirmation

Looking to create a custom Angular directive using angular-bootstrap that mimics the confirm() function. Check out the visual result and desired behavior in this plunk: http://embed.plnkr.co/27fBNbHmxx144ptrCuXV/preview Now, I want to implement a directi ...

Using additional properties when referencing another Mongoose schema

var UserSchema = new Schema({ job : [{ type : mongoose.Schema.Types.ObjectId, experience : String, grade : String, ref: 'Company'}] }); User's profile can include multiple jobs. The process of adding a job to the user is a ...

Troubleshooting Issue with Ionic's UI Router

Recently, I created a basic Ionic app to gain a better understanding of UI router functionality. To my surprise, when I ran the app, nothing appeared on the screen. Additionally, the developer tools in Google Chrome did not show any errors or information. ...