我嘗試以特定方式元素添加到下面的JSON元素添加到一個JSON的一部分:我如何通過使用jQuery
var data = [{"name":"google",
"ip":"10.10.10.01",
"markets":[{"name":"spain","county":"6002,6017,6018,6019,6020"},
{"name":"france","county":"6003,6005,6006,6007,6008,6025,6026,6027,6028,6029"},
{"name":"japan","county":"6004,6021,6022,6023,6024"},
{"name":"korea","county":"6000,6013,6014,6015,6016"},
{"name":"vietnam","county":"6001,6009,6010,6011,6012"}]},
{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"usa","county":"10000,10001,10002,10003,10004,10005"}]},
{"name":"yahoo",
"ip":"10.10.10.03",
"markets":[{"name":"japan","county":"10000"}]}];
我想這個元素添加到JSON:
newData = [{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"mexico","county":"9000"}]}];
結果可能是正是這一點:
var data = [{"name":"google",
"ip":"10.10.10.01",
"markets":[{"name":"spain","county":"6002,6017,6018,6019,6020"},
{"name":"france","county":"6003,6005,6006,6007,6008,6025,6026,6027,6028,6029"},
{"name":"japan","county":"6004,6021,6022,6023,6024"},
{"name":"korea","county":"6000,6013,6014,6015,6016"},
{"name":"vietnam","county":"6001,6009,6010,6011,6012"}]},
{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"usa","county":"10000,10001,10002,10003,10004,10005"},
{"name":"mexico","county":"9000"}]},
{"name":"yahoo",
"ip":"10.10.10.03",
"markets":[{"name":"japan","county":"10000"}]}];
我試着使用:
$.extend(data.markets, newData)
$.extend(true, data, newData);
//這隻適用於每個元素都是新的情況。
但沒有任何工作,我假裝的方式。
任何人都可以給我一個解決方案嗎?
在此先感謝。
FYI,你發佈的是一個包含對象,而不是JSON的JavaScript數組。 '.extend(data.markets,newData)'不起作用,因爲'data'是一個數組,並且數組沒有'markets'屬性。 '.extend(true,data,newData)'不起作用,因爲'data'是一個數組,並且你正試圖向數組添加屬性'name','ip'和'markets'沒有意義。你實際上必須做的是遍歷'data'來找到名稱和ip匹配的對象,併合並它們的'''''''數組。 –
是的,奇怪的JavaScript對象表示法並不是指用於表示JavaScript對象的符號... – Jeff