简体   繁体   中英

Creating javascript object with dynamic key from the accessed array element

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.

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)

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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM