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

236
Visualizações
Why does this function returns modified object even though replacement is triggered by recursive call which uses a new object?

I'm trying to trace and figure out the following code.

const strip2 = (object, path) => {
  const keys = [path];
  const pathArray = keys[0].split('.');

  pathArray.reduce((prevObj, key, index) => {
    if (!prevObj[key]) {
      return null;
    }
    if (Array.isArray(prevObj[key])) {
      return prevObj[key].map(item => strip2(item, pathArray[index + 1]));
    }
    if (index === pathArray.length - 1) {
      prevObj[key] = prevObj[key].replace('/hello', '');
    }
  }, object);

  return object;
};

strip2(
  {
    title: 'this is the title',
    menu: [
      {
        link: '/hello/contact',
        title: 'Contact Us',
      },
      {
        link: '/hello/faq',
        title: 'Faq',
      },
    ],
  },
  'menu.link'
);

\\ it will return
{
  title: 'this is the title',
  menu: [
    { link: '/contact', title: 'Contact Us' },
    { link: '/faq', title: 'Faq' }
  ]
}

As you can see, the replace function is only triggered by the recursive call which uses a new object but the original object is changed.

about 4 years ago · Juan Pablo Isaza
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