This question is a little odd because PHP arrays are more like objects in Javascript then actual arrays. The biggest difference is syntactic:
Here is a solution that matches the provided example:
let a = 4
let keys = ["a", "b", "c"]
// Same as the PHP code, loop backwards
for(let i = keys.length - 1; i >= 0; i--) {
let key = keys[i]
// Create a new object with the key and the old a as the value.
a = { [key]: a }
}
A more functional approach would be to use Array#reduce
:
let a = 4
let keys = ["a", "b", "c"]
let result = keys
.reverse()
.reduce((value, key) => ({ [key]: value }), a)
EDIT
A slightly better approach is to use Array#reduceRight
. This will let you just have the final value you in the array:
let keys = ["a", "b", "c", 4]
let result = keys.reduceRight((v, k) => ({ [k]: v }))