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

106
Views
¿Cómo establecer el valor del objeto multidimensional cuando la ruta del nombre se almacena en una matriz de longitud desconocida?

Tengo una matriz de longitud desconocida que define la ruta al contenido que quiero modificar en un objeto.

Esto es lo que quiero.

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

Mi problema es que myArray tiene una longitud desconocida. ¿Cuál es la mejor manera de actualizar un valor en el objeto?

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

0

Aquí hay un enfoque feo usando una función recursiva. La idea es recuperar las propiedades anidadas en secuencia, llamando a la función recursivamente con el nivel actual, hasta el final de la matriz:

 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!