1

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.

Sunil
  • 3,404
  • 10
  • 23
  • 31
  • What have you tried so far and can you provide a visual of `$value` and other relevant variables, also give the expected output. – NewToJS Mar 22 '18 at 01:52
  • Do you understand what the code does? Now reimplement it. – user202729 Mar 22 '18 at 01:59
  • 2
    JavaScript has separate types for collections with named keys (`Object`) and those with sequential indexes (`Array`), whereas PHP combines both styles into `array()`s. – Related: [Best way to store a key=>value array in JavaScript?](https://stackoverflow.com/questions/1144705/best-way-to-store-a-key-value-array-in-javascript) and [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – Jonathan Lonowski Mar 22 '18 at 02:01
  • Your code in PHP doesn't even make sense since you're overwriting `$a` on every iteration of the `for` loop. – Mike Mar 22 '18 at 02:05
  • @Mike It embeds the previous `$a` (value or array) into the next, appearing to build a set of arrays from the inside out – `array(key0 => array(key1 => array(key2 => $value)))`. – Jonathan Lonowski Mar 22 '18 at 02:07
  • @JonathanLonowski Ah, I missed the `$a` at the end. You're absolutely right. – Mike Mar 22 '18 at 02:09
  • Use `json_encode()` & `json_decode()` for php & `JSON.parse` & `JSON.stringify` in JS. JS doesn't have associative arrays, but you can use Objects as those. – admcfajn Mar 22 '18 at 02:51
  • Babel has supported https://babeljs.io/php/ – Vuong Apr 03 '18 at 02:59

1 Answers1

1

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 }))
ncphillips
  • 736
  • 5
  • 16