Substitute the nested object's value with a variable structure

I have an object structured like this:

const obj = {a: {x: 0, y: 0}}

but it can also be structured like this:

const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}}

This means that the obj can contain multiple keys with variable key names. I want to replace each x value with a string in the format ${x}%, where x is the original value followed by a percentage symbol.

How can I achieve this transformation?

The expected output should look like:

const obj = {a: {x: 0, y: 0}} // {a: {x: '0%', y: 0}}
const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}} // {a: {x: '0%', y: 0}, b: {x: '10%', y: 3}, abcd: {x: '-1%', y: 0}}

I attempted looping through the object but I'm unsure if there is a more efficient solution available.

Answer №1

const myObj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}}

let updatedObj = Object.fromEntries(Object.entries(myObj).map(([key,value]) => {
    return [key,{...value,x:`${value.x}%`}]
}))

console.log(updatedObj)

Answer №2

Exploring the object recursively is another approach. This method ensures that every matching key receives a corresponding suffix, regardless of the depth of the object.

To maintain the integrity of the original object(s), I always create a duplicate before processing any modifications.

const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}};

const addSuffixToObj = (obj, key, suffix) => {
  const copy = {...obj};

  Object.keys(copy).forEach((prop) => {
    if (typeof copy[prop] === 'object') {
      copy[prop] = addSuffixToObj(copy[prop], key, suffix);
    }else if(prop === key){
      copy[prop] = copy[prop] + suffix;
    }
  });
  
  return copy;
}

// Append "%" to all "x" keys
const result = addSuffixToObj(obj, 'x', '%');

console.log(result);

Answer №3

If you want to modify the values of object keys, one way to do it is by getting the array of object keys and then using the forEach method. This method executes a provided function for every element of the array, in this case - for every object key:

Object.keys(obj).forEach(element => obj[element].value = `${obj[element].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

Tips for saving an array from the server into a script variable

I'm currently working with the express js framework along with Handlebarsjs as the templating engine. My aim is to pass an array from the router to the view, and then store this array within a script tag. //users is an array res.render('chatRoom ...

The component encounters a transformation in which prop values shift to undefined

My component seems to be encountering some instability. The value assigned to "this.state.list" from this.props is being immediately set to "undefined". I'm struggling to comprehend why this is happening. Can anyone spot the issue in the code? this.s ...

Creating seamless online payments using Stripe and Bootstrap

I'm new to integrating Stripe for payment processing on my Bootstrap website and currently utilizing Stripe.js v2. As far as I understand, the process involves my HTML form communicating with Stripe via JavaScript to obtain a token (or handle any err ...

Eliminate Video Time Indicator

Can the video progress bar be removed from this specific video player? I would like it to be integrated into the embed code that I share with others. <iframe id="hapyak-player-157199-8825" marginwidth="0" marginheight="0" frameborder="no" scrolling=" ...

Trigger a warning pop-up if a selection has not been made in a dropdown menu using jQuery

I am attempting to display an alert popup when the user fails to select a value from the dropdown menu. Below is my HTML code: <div id="reminder" class="popup-layout"> ... ... </form> </div> In my JavaScript function page, I have tried ...

I am currently working on creating a navigation bar for a webpage using the express framework and pug library. However, when I navigate to the demo page endpoint, the screen appears blank and nothing is displayed

//In the following JavaScript code, I am trying to implement basic routing navigation using express. However, when I try to insert HTML into the demo page, nothing appears on the browser screen. const path = require("path"); const app = ...

Creating a menu header similar to Gmail's design is a great way to

How can I create a fixed menu similar to the one in Gmail? I've attempted using CSS, but the div remains centered instead of sliding up on scroll like the Gmail menu. View in full-size image I've experimented with CSS properties, here's an ...

Proper method for retrieving and displaying information from a targeted JSON through an API

Utilizing a third-party API requires specifying the desired fields in the request. For instance: axios.get("APIURL", { params: { fields: ["username", "phone", ...etc] } }) The response is typically structured like this: { "data": [{ ...

Export all entries without taking into account pagination limits

My current setup involves using Datatables with pagination. I recently integrated the Datatable.buttons library to enable an Export to Excel feature. However, I encountered a limitation where only the first 10 rows on the current page are exported due to p ...

JQuery Mobile: Adding fresh, dynamic content - CSS fails to take effect

I've encountered this issue before, but I'm still struggling to resolve it. When adding dynamic content to a page (specifically a list-view), the CSS seems to disappear once the content is added. I've tried using the trigger("create") functi ...

Is there a way to modify the log() function to handle multiple arguments?

Recently, I've been utilizing this logger in node.js: // Found on stackoverflow: https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color function logC(text) { console.log('\x1b[36m%s\x1b[0m', text); ...

There seems to be an issue with AJAX file uploading functionality in Django

I'm facing an issue with uploading files using the onchange event and AJAX. I am only able to get the file path on the backend, not the actual file itself. My goal is to modify the code so that when a PDF file is selected, it automatically gets upload ...

Struggling to transfer the loaded data into the corresponding text fields for display

I'm currently working on a project where I need to extract data stored in an object and showcase it on my website. In my .html file, I have the following setup: <script type="text/javascript"> var res = {"address":"","city":"","state":"","z ...

Issue: Query is not re-executing after navigatingDescription: The query is

On my screen, I have implemented a query as follows: export const AllFriends: React.FunctionComponent = () => { const navigation = useNavigation(); const { data, error } = useGetMyProfileQuery({ onCompleted: () => { console.log('h ...

What can be done to resolve the error message "This language feature is only supported for ECMASCRIPT6 mode" in Google Tag Manager?

I attempted to implement some JavaScript code in GTM, but encountered an error. The error occurs at this line window.sbHooks.addAction('sbCoreState::CreateBets/success', (data, response) => { where I utilized a custom Vue.js hook. How can I ...

Can you choose and generate identical values using react-select?

I am working on implementing a multi Creatable feature where users can select a preset value or create a new value during the same interaction. To illustrate, here is my current render: import CreatableSelect from 'react-select/creatable'; functi ...

Mastering EmberJS 2.7: The Definitive Guide to Binding the 'disabled' Attribute for Buttons

Here is an official guide explaining how to bind a boolean property to the disabled attribute of an HTML element. However, it references a controller in the process. I have a button that, when clicked, transitions the route (it must be a button and not a ...

Can I use JavaScript to generate an element similar to <ion-icon name="heart"></ion-icon>?

Currently, I am utilizing a website called to incorporate icons into my buttons. It is quite straightforward with HTML when introducing a new element containing the icon. All you need to do is define a button and insert this code within it: ion-icon name= ...

What is the most efficient method for adding each unique unordered list element with a specific class to the nearest parent article tag

The current code structure looks like this: <article id="post-529"></article> <ul class="post-meta"></ul> <article id="post-530"></article> <ul class="post-meta"></ul> <article id="post-531"></a ...

Retrieve data using $http.get when an accordion group is expanded in AngularJS

Currently, I am utilizing Angular v1.2.0rc1 along with Angular-UI Bootstrap. [edit] My objective is to implement a load-on-demand feature with caching while incorporating an accordion functionality. The accordion group that I am using can be found here. ...