Add dynamic key, value pairs to JavaScript array or hash table

前端 未结 5 1627
醉话见心
醉话见心 2020-12-12 19:51

I\'m trying to add a key value pair to an existing javascript associative array. The key needs to be a variable. This is for JSON encoding. I realize there are many plugins

5条回答
  •  醉酒成梦
    2020-12-12 20:18

    In ES6...

    In ES6, you can use a destructuring assignment;

    ary.push({[name]: val});
    

    However, given this is ES6 syntax, the usual caveats apply; this will not work in some browsers (noticably, IE and Edge 13)... although Babel will transpile this for you.


    Without ES6 (legacy browser support)...

    You need to define an object and use square bracket notation to set the property;

    var obj = {};
    
    obj[name] = val;
    
    ary.push(obj);
    

    If you get the urge to read into it more, see this article on the differences between square bracket and dot notation.

提交回复
热议问题