2014-08-27 57 views
-1

如何更改動態嵌套javascript對象中屬性的值?如何使用javascript更改嵌套對象中的值

對象: "chart": { "height": 400, "width": 600, "margin":{"top": 0, "right": 0, "bottom": 0, "left": 0},
"padding":{"top": 0, "right": 0, "bottom": 0, "left": 0}, "grid" : { "xEnabled":"yes", "yEnabled":"yes", "color": "#ddd" } },

我怎樣才能使用JavaScript padding.top改變從0到20。

任何代碼都會有幫助。

+0

看看這個:http://css-tricks.com/forums/topic/need-help-with -javascript-inheritance-and-nested-objects/ – ctwheels 2014-08-27 19:12:18

+0

我修改了一下我的問題。改變的關鍵和價值來自變量。那麼我們應該如何實現它? – 2014-08-27 19:19:03

回答

0
var whatKey = 'top'; 
var whatValue = 20; 

var myObject = {"chart": { 
      "height": 400, 
      "width": 600, 
      "margin":{"top": 0, "right": 0, "bottom": 0, "left": 0}, 

      "padding":{"top": 0, "right": 0, "bottom": 0, "left": 0}, 
      "grid" : { 
       "xEnabled":"yes", 
       "yEnabled":"yes", 
       "color": "#ddd" 
      } 
    } 
}; 
myObject.chart.padding[whatKey] = whatValue; 
alert(JSON.stringify(myObject)); 

參見:http://jsfiddle.net/qc18kfmj/

+0

我修改了一下我的問題。改變的關鍵和價值來自變量。那麼我們應該如何實現它? – 2014-08-27 19:19:45

+0

要用變量指定屬性名稱,請使用下標語法。 (OBJ [PROPERTYNAME])。 – folkol 2014-08-27 19:27:29

+0

我根據你的新問題更新了答案。 – folkol 2014-08-27 19:28:20

0

您可如下更改:

var c = { 
     "chart": { 
      "height": 400, 
      "width": 600, 
      "margin": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, 

      "padding": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, 
      "grid": { 
       "xEnabled": "yes", 
       "yEnabled": "yes", 
       "color": "#ddd" 
      } 
     } 
    }; 
    c['chart']['padding']['top'] = 20; 

    alert(c['chart']['padding']['top']); 
相關問題