Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Replace value of nested object with variable structure

I've an object like this:

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

that could be also:

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

So, the obj can have more than one key and with variables key names. I need to replace each x value with a a string like this ${x}% so the x value + the percentage symbol.

How can I do that?

The expected results should be:

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 tried looping the object but I don't know if there is a smartest solution

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

let result = Object.fromEntries(Object.entries(obj).map(([k,v]) => {
    return [k,{...v,x:`${v.x}%`}]
}))

console.log(result)

about 4 years ago · Juan Pablo Isaza Report

0

You can also check the object recursively. So no matter how deep the object goes every given key that matches gets a suffix.

I also make sure to create a copy of the object to prevent altering the original object(s).

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;
}

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

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

You can get the array of object keys and then use forEach, it's a method that executes provided function for every element of array(here - for every object key):

Object.keys(obj).forEach(el => obj[el].x = `${obj[el].x}%`)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!