var myObj = {
bar_foo : "test",
bar : {
foo : "hi there";
},
foo : {
bar : {
foo: "and here we go!"
}
}
}
How can we achieve the following:
var arr = [["bar", "foo"], ["foo", "bar", "foo"]];
to produce these results:
myObj["bar"]["foo"];
myObj["foo"]["bar"]["foo"];
The array arr
may vary in length, allowing it to explore the object fully.
We are aware that we can access an object's value dynamically as shown below:
var normally = myObj["bar_foo"];
where normally
would be equal to "test"
However, this method assumes a predetermined depth for traversing the object.
I am attempting to retrieve an object's value by providing an array such as:
["bar", "foo"]
This is essentially equivalent to:
myObj["bar"]["foo"];
The objective behind this approach is to create a new object based on specific values extracted from arr
.
Consequently, the final outcome would be:
arr_new = myObj.someMethod(arr);
where arr_new
represents:
arr_new : ["hi there", "and here we go!"];
Hopefully, this explanation provides clarity on the matter.