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

241
Views
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
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!