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

85
Views
Re-usable javascript function with variable object path name passed on as a parameter?

I am trying to write a re-usable javascript function to insert key/value pairs into variable path locations within an object. Assume I have an object like this.

const obj ={
  firstName: 'Bob',
  lastName: 'Smith'
}

I have created a re-usable function like so

function mapData(doc, path) {
  const keyNames = Object.keys(doc);
  const bigDoc = {};

  keyNames.forEach(keyname => {
    bigDoc[keyname] = doc[keyname];
  });

  return bigDoc;
}

Now I want to be able to place it under the correct path under bigDoc, like for example bigDoc.teacher.math or bigDoc.student.yearten by calling the method mapData(obj, 'teacher.math') or mapData(obj, 'student.yearten') so that, for example, bigDoc.teacher.math.firstName is set to 'Bob. I know how to do it with one level deep, but I don't know how for two or more levels deep.

Please help.

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!