如何使对象键的名称成为变量的值?

时间:2018-10-10 19:38:29

标签: javascript

var orderName = document.getElementById("orderName").value;
var order = ["5", "6"];
var Orders: {
    orderName: order
}
JSON.Stringify(Orders); // returns {"ordername":[5,6]}
//Expected output would be {"Hamburger": [5,6]}

当调用JSON.Stringify(Orders)时,如何返回元素的值?

1 个答案:

答案 0 :(得分:1)

使用方括号属性表示法:

var orderName = "Hamburger";
var order = ["5","6"];

var obj = { [orderName]: order }; 

console.log(obj);