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

147
Views
Reemplace todas las propiedades del objeto anidado a un valor particular

¿Escriba una función que debería tomar una matriz de objetos y debería reemplazar un valor particular de la clave?

por ejemplo: en el objeto a continuación, todo el valor de "bar" debe reemplazarse por "foo-bar"

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

Nota: Todas las propiedades de objetos anidados también deben reemplazarse

almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Recorra recursivamente todas las claves.

 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!