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

98
Views
How to set value of multidimential object when name path is stored in array of unknown length?

I have an array of unknown length which defines the path to content I want to alter in a object.

This is what I want.

let updatedContent = "Hello World!";
let myArray = ["layer1","layer2","layer3"];
myObject["layer1"]["layer2"]["layer3"] = updatedContent;

My problem is myArray is of unknown length. What is the best way to update a value in the object?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Here's an ugly approach using a recursive function. The idea is retrieving the nested properties in sequence, calling the function recursivelly with the current level, until the end of the array:

function changeObject(obj, arr, content, index = 0) {
  if (index < arr.length - 1) {
    changeObject(obj[arr[index]], arr, content, ++index);
  } else {
    obj[arr[index]] = content;
  }
};

const myObject = {
  layer1: {
    layer2: {
      layer3: "foo"
    }
  }
};

let updatedContent = "Hello World!";
let myArray = ["layer1", "layer2", "layer3"];
myObject["layer1"]["layer2"]["layer3"] = updatedContent;

changeObject(myObject, myArray, updatedContent);
console.log(myObject);

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