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.

8
  • What have you tried so far and can you provide a visual of $value and other relevant variables, also give the expected output. Commented Mar 22, 2018 at 1:52
  • Do you understand what the code does? Now reimplement it. Commented Mar 22, 2018 at 1: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? and How to use a variable for a key in a JavaScript object literal? Commented Mar 22, 2018 at 2:01
  • Your code in PHP doesn't even make sense since you're overwriting $a on every iteration of the for loop. Commented Mar 22, 2018 at 2: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))). Commented Mar 22, 2018 at 2:07

1 Answer 1

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 }))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you guys for your response. I tried today also. I was trying like for(int i=0;i<a.length; i++) { tmp[a[i] = {}; tmp = tmp[a[i]] } . It didnt work. and finally used reduce method. But the answer by ncphillps is much shorter and precise. Thank you so much for your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.