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

155
Views
Replace all the nested object properties to particular value

Write a function that should take an array of objects and it should replace a particular value of the key?

for example: in below object, all the value of "bar" should be replaced to "foo-bar"

let obj = {
  a: "foo",
  b: "bar",
  c: {
    d: "foo",
    e: "bar",
    f: {
      g: "test",
      h: "bar",
    }
  }
}

Note: All the nested object properties also needs to be replaced

almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Recursively loop through all the keys.

const obj = {
  a: 'foo',
  b: 'bar',
  c: {
    d: 'foo',
    e: 'bar',
    f: {
      g: 'test',
      h: 'bar',
    },
  },
};

function replaceValuesInObj(o, targetValue, replaceValue) {
  Object.keys(o).forEach((key) => { // forEach key in the object
    if (o[key] === targetValue) o[key] = replaceValue; // is the value your condition? set it to 'foo-bar'
    if (typeof o[key] === 'object' && o[key] !== null) { // if the key is an object (call the function recursively)
      replaceValuesInObj(o[key], targetValue, replaceValue);
    }
  });
}

replaceValuesInObj(obj, 'bar', 'foo-bar');
console.log(obj);

almost 4 years ago · Santiago Trujillo 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!