Update
Thank you all for your inputs, thanks to you I realize now I've made a seriously wrong assumption about JS. Actually, the code provided below works fine, if one modifies it:
...
let currentPlaceInArray;
for (let i = 0; i < position.length; i++) {
let place = position[i];
if (i + 1 === position.length) return currentPlaceInArray[place] = content; // Added this line now
/***Explanation:
Without this added line, the currentPlaceInArray variable is reassigned in the end
to 'needle' in the present example. Thus, assigning it to something else (like
currentPlaceInArray = ['updated']) will not have any effect on the array, because
currentPlaceInArray is not assigned to it anymore, it's assigned to the string 'needle'
***/
currentPlaceInArray = currentPlaceInArray ? currentPlaceInArray[place] : myArray[place];
}
Original problem
I have a large unstructured multidimensional array, I do not know how many nested arrays it has and they have different lengths, like in this simplified example:
var myArray =
[
[
[],[]
],
[
[],[],[],[]
],
[
[],
[
[
['needle']
]
]
]
];
I want to be able to update 'needle' to something else. This would be possible by executing myArray[2][1][0][0] = 'updated';
I want to create a function which takes as parameters just 2 pieces of information: 1) the string to be written and 2) an array with the position of the array item to be updated. In the above case of myArray, it would be called thus: changeNeedle('updated', [2, 1, 0, 0]).
However, I can't assign a variable to an array key, just to its value. If it was possible to assign a variable to the array key, I could just update that variable with the current position (i.e., [Update: it's the exact opposite, assigning a variable to an array will point exactly to that array, so var currentPosition would be myArray[x], and currentPosition[y] would then be myArray[x][y])currentPosition[y] === myArray[x][y]]. Like so:
function changeNeedle(content, position) {
/***
content: a string
position: an array, with the position of the item in myArray to be updated
***/
let currentPlaceInArray;
for (let i = 0; i < position.length; i++) {
let place = position[i];
currentPlaceInArray = currentPlaceInArray ? currentPlaceInArray[place] : myArray[place];
}
currentPlaceInArray = content;
}
Is it possible to implement this changeNeedle function without using eval, window.Function() or adding a prototype to an array?