Search code examples
javascriptphpobjectassign

can JS automatically assign keys like PHP?


in PHP, keys can automatically be assigned without requiring a name or variable:

$myObject = ['someCrap' =>[]];
for($i=0;$i<=10;$i++) {
  $myObject['someCrap'][] = 90 * $i;
};
var_dump($myObject);

can this be done in Javascript? i've tried the following code:

let myObject = {'someCrap':{}}
for(let i=0;i<=10;i++) {
  myObject['someCrap'][] = 90 * i
}
console.log({myObject})

which yields Uncaught SyntaxError: expected expression, got ']'. is there a way to make this happen without using counters, or is that the only way to do this?


Solution

  • You need to use an array, not an object. The JS equivalent of assigning to [] is the .push() method.

    let myObject = {
      'someCrap': []
    }
    for (let i = 0; i <= 10; i++) {
      myObject['someCrap'].push(90 * i)
    }
    console.log(myObject)