2014-04-12 115 views
0

我有以下對象:追加對象到子對象的JavaScript

var dpsets = { 
    "routes": [ 
     { 
      "name": "first", 
      "values": [ 
       "info", 
       "more info", 
       "text" 
      ] 
     }, 
     { 
      "name": "second", 
      "values": [ 
       "text again", 
       "with info" 

      ] 
     } 
    ] 
} 

我也有以下對象:

var currentSet = { 
    "name": "New Route", 
    "values": [ 
     "Latest one", 
     "Latest two" 
    ] 
} 

我想追加currentSetdpsetsroutes元素。

我已經嘗試了dpsets.routes.push(currentSet)和jQuery的$.extend(dplocations.routes, currentRoute),但似乎沒有做我所需要的。

這樣做的最佳方法是什麼?

+2

「dpsets.routes.push(currentSet);」爲我工作。 –

+1

檢查它是否工作.. - http://jsfiddle.net/zPzY3/ –

+1

什麼不適合你''dpsets.routes.push(currentSet)''嗎? – Michael

回答

0

本來這沒有奏效:

dpsets.routes.push(currentSet)

然而,再次嘗試之後,它工作得很好。

0

試戴

dpsets.routes.push((currentSet)); 

alert(JSON.stringify(dpsets)); 

fiddle

-1

你嘗試使用的方法CONCAT()?

dpsets.concat(currentSet)

0
var dpsets = { 
"routes": [ 
    { 
     "name": "first", 
     "values": [ 
      "info", 
      "more info", 
      "text" 
     ] 
    }, 
    { 
     "name": "second", 
     "values": [ 
      "text again", 
      "with info" 

     ] 
    } 
] 
}; 
var currentSet = { 
    "name": "New Route", 
    "values": [ 
     "Latest one", 
     "Latest two" 
    ] 
}; 

dpsets.routes.push(currentSet); 
console.log(dpsets); 

Demo