IT TIP

JavaScript 객체 리터럴에서 변수 키를 사용하는 방법이 있습니까?

itqueen 2020. 10. 30. 21:18
반응형

JavaScript 객체 리터럴에서 변수 키를 사용하는 방법이 있습니까?


나는 이와 같은 코드가 있습니다.

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

나는 그것을 key"anything" 으로 대체 할 방법이 있는지 알고 싶다 .

처럼

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

예. 당신이 사용할 수있는:

var key = "anything";
var json = { };
json[key] = "key attribute";

또는 프로그램을 작성할 때 손에 값이 있으면 두 번째 방법을 사용하십시오.


ES6에서는 계산 된 속성 이름을 사용 합니다 .

const key = "anything";   

const object = {   
    [key]: "key attribute"
//  ^^^^^  COMPUTED PROPERTY NAME
};

주위의 대괄호에 유의하십시오 key. 실제로 변수뿐만 아니라 대괄호 안에 모든 표현식을 지정할 수 있습니다.


이것은 트릭을 수행해야합니다.

var key = "anything";

var json = {};

json[key] = "key attribute";

최신 자바 스크립트 (ECMAScript 6)에서는 대괄호로 변수를 둘러 쌀 수 있습니다.

var key = "anything";

var json = {
    [key]: "key attribute"
};

해결책:

var key = "anything";

var json = {};

json[key] = "key attribute";

클로저는이를 위해 잘 작동합니다.

function keyValue(key){
  return function(value){
    var object = {};
    object[key] = value;
    return object;
  }
}

var key = keyValue(key);
key(value);

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');

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!

참고URL : https://stackoverflow.com/questions/882727/is-there-a-way-to-use-variable-keys-in-a-javascript-object-literal

반응형