-1
let a = "1,2,3".split(",");
let b = {a[0]: a[1]};

expression {a[0]: a[1]) fetches Uncaught SyntaxError: Unexpected token '['

but {"s": a[1]} or even when "s" is stored in var it works.

Just curious about this.

  • 3
    Does this answer your question? [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – Ivar Jun 09 '20 at 07:54
  • 3
    `{[a[0]]: a[1]}` – Ivar Jun 09 '20 at 07:54

2 Answers2

2

You have to change it to this way to create dynamic key name:

    let a = "1,2,3".split(",");
    let b = {[a[0]]: a[1]}; // notice the extra [] wrapping a[0]

        let a = "1,2,3".split(",");
        let b = {[a[0]]: a[1]}; // notice the extra [] wrapping a[0]
        
        
        console.log(b)
ABGR
  • 4,631
  • 4
  • 27
  • 49
0

Dynamically add values to create hashMap of key: value

var splittedArray =  "1,2,3".split(",");
  var hashMap= {};
  for (let key in splittedArray) {
    if( splittedArray.length -1 === key)
        hashMap[key] = splittedArray[key];
    hashMap[+key+1] = splittedArray[key]
  }

  console.log(hashMap);
// Output: {1: "1", 2: "2", 3: "3"}
khizer
  • 1,242
  • 15
  • 13