2014-01-07 141 views
0

我有這樣的,看起來像這樣合併JSON對象爲單一對象的數組使用jquery

[{ 
    "Name": "Nikhil", 
    "Surname": "Agrawal" 
}, { 
    "profession": "java developer", 
    "experience": "2 years" 
}, { 
    "company": "xyz", 
    "city": "hyderabad" 
}] 

JSON對象的數組,現在我所試圖做的是結合整個陣列爲單JSON對象

{ 
    "Name": "Nikhil", 
    "Surname": "Agrawal" 
    "profession": "java developer", 
    "experience": "2 years" 
    "company": "xyz", 
    "city": "hyderabad" 
} 

我這個jQuery.merge(firstObject, secondObject)嘗試,但它再次所以我需要申請循環和交換的對象等等複雜的邏輯只需要兩個參數。有沒有其他的方式來合併這?

+0

那你試試??? – Hiral

+0

@GeorgeStocker可能有其他重複,但這裏標記的是關於創建一個新的數組 –

回答

1

我不認爲它可以在一個單一的呼叫進行,以儘量

var obj = {}; 
$.each(arr, function (i, o) { 
    $.extend(obj, o) 
}) 
console.log(obj) 

演示:Fiddle

+0

先生謝謝。你第二次幫我。爲你+1。 –

2

的Javascript

var json = [{ 
    "Name": "Nikhil", 
    "Surname": "Agrawal" 
}, { 
    "profession": "java developer", 
    "experience": "2 years" 
}, { 
    "company": "xyz", 
    "city": "hyderabad" 
}]; 

var newObj = {}; 
for(var i = 0; i < json.length; i++){ 
    for(x in json[i]){ 
     console.log(x); 
     newObj[x] = json[i][x];  
    } 
} 

JS小提琴:http://jsfiddle.net/wVGah/

1

使用jQuery .extend功能是這樣的:

var json = [{"Name": "Nikhil","Surname": "Agrawal"},{"profession": "java developer","experience":"2 years"},{"company": "xyz","city":"hyderabad"}]; 

var json2 = json[0]; 

for(var i = 1; i<json.length; i++){ 
    $.extend(json2,json[i]); 
} 

Here is a working Fiddle