2017-01-16 50 views
-3

我有這樣更改對象的屬性基於可變

{"first":["first 1"],"second":["second 1","second 2"],"third":["third 1", "third 2"]} 

我希望能夠改變基於變量值的屬性名稱的對象。 如果變量是「秒」,它應該改變屬性秒到任何我想要的。 我已經試過一些方法...

object[theVariable] = "new second"; 

將屬性的值更改爲這個

{"first":["first 1"],"second":"new second","third":["third 1", "third 2"]} 

object.theVariable = "new second"; 

將創建一個新的像這樣的財產

{"first":["first 1"],"second":["second 1","second 2"],"third":["third 1", "third 2"],"theVariable":"new second"} 

這些方法都不能更改屬性「第二」到「新的第二」時,「第二」被存儲在變量「theVariable」

期望的結果:

{"first":["first 1"],"new second":["second 1","second 2"],"third":["third 1", "third 2"]} 

這怎麼可能做了什麼?

+0

@melpomene:好像是OP希望的關鍵,更換 –

+0

您的代碼不你想要什麼,我沒有看到問題。 –

+2

[change property name](http://stackoverflow.com/questions/8483425/change-property-name) – melpomene

回答

1

如果我的理解正確,您想要更改對象中屬性的名稱。這應該工作。通過括號標記

object.new_second = object.second; 
delete object.second 
-2

使用屬性訪問:

var obj = { 
 
     "first":["first 1"], 
 
     "second":["second 1","second 2"], 
 
     "third":["third 1", "third 2"] 
 
    }; 
 
    console.log(obj); 
 
    var propNameVariable = "second"; 
 
    obj[propNameVariable] = "new second"; 
 
    console.log(obj);

+0

這不會將「second」更改爲「new第二」。這只是取代價值 – Koiski

+0

@Koiski - 你是說你想讓代碼明白新屬性的名稱是「new」+ <舊屬性的名稱>',刪除舊屬性並設置新屬性? – Igor

+0

@Igor查看更新後問題中的「所需結果」。 – melpomene

1

var obj = {"first":["first 1"],"second":["second 1","second 2"],"third":["third 1", "third 2"]}; 
 

 
var theVariable = "new second"; 
 

 
obj[theVariable] = obj.second; 
 
delete obj.second; 
 

 
console.log(obj);

+0

@Koiski更新回答! – Weedoze