1

There is a way to pass a string in a function to other function and this string is a reference to an object in this other function?

function fun1 (structure){ 
obj = [{"header":{"orderNumber": a, "item": 1}}, {"header":{"orderNumber": b, "item": 1}}]

newObj = obj[0].structure


console.log(newObj) 
//first call a
//second call 1

}

//first call
function fun2(){

   structure = 'header.orderNumber'
   fun1(structure)
}

//second call
fun2(){

   structure = 'header.item'
   fun1(structure)
}

What I want is a dynamic way to access an object by creating a string. For example in the block of code obj.header.item.description and this is valid. I would like to pass a string in this string somehow make a reference to the object so I can get the value.

  • 1
    Check what fits you best here: https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arrays-by-string-path – n-- Oct 05 '22 at 17:53
  • [There's many ways](https://stackoverflow.com/a/14397052/1048572), but you probably shouldn't be doing this. What do you need this for? – Bergi Oct 05 '22 at 21:00

1 Answers1

0

One way you could accomplish this would be by storing all of the object references in a Map (MDN) structure where the key is a string and the value is the object reference in question.

I should say that even though I don't know your exact use case, this is what you would call a "stringly typed" solution which is generally not the best idea.

Nathan Wiles
  • 841
  • 10
  • 30