Reputation: 9
How can I convert this PHP code to JavaScript code? I am not sure about array()
method and =>
symbol.
Here is the code:
$a = $value;
for ($i = count($keys)-1; $i>=0; $i--) {
$a = array($keys[$i] => $a);
}
Create nested array by array of keys. This is the question I am looking to get it done in java script. I have been trying so many ways but got no success.
Your help is appreciated.
Upvotes: 1
Views: 191
Reputation: 736
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 }))
Upvotes: 1