Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda