Is there a way to use variable keys in a JavaScript object literal?

前端 未结 8 2248
暗喜
暗喜 2020-11-27 13:38

I have code like this.

var key = \"anything\";   
var object = {   
    key: \"key attribute\"  
};

I want to know if there is a way to rep

相关标签:
8条回答
  • 2020-11-27 14:26

    Well, there isn't a "direct" way to do this...

    but this should do it:

    json[key] = json.key;
    json.key = undefined;
    

    Its a bit tricky, but hey, it works!

    0 讨论(0)
  • 2020-11-27 14:31

    Recently needed a solution how to set cookies passing the dynamic json key values. Using the https://github.com/js-cookie/js-cookie#json, it can be done easily. Wanted to store each selected option value of user in cookie, so it's not lost in case of tab or browser shutting down.

    var json = { 
            option_values : {}
        };
        $('option:selected').each(function(index, el) {
            var option = $(this);
            var optionText = option.text();
            var key = 'option_' + index;
            json.option_values[key] = optionText;
            Cookies.set('option_values', json, { expires: 7 } );
        }); 
    

    Then you can retrieve each cookie key value on each page load using

    Cookies.getJSON('option_values');
    
    0 讨论(0)
提交回复
热议问题