我有一个像这样的json对象数组,看起来像这样
[{
"Name": "Nikhil",
"Surname": "Agrawal"
}, {
"profession": "java developer",
"experience": "2 years"
}, {
"company": "xyz",
"city": "hyderabad"
}]
现在我要做的是将整个数组合并为单个json对象
{
"Name": "Nikhil",
"Surname": "Agrawal"
"profession": "java developer",
"experience": "2 years"
"company": "xyz",
"city": "hyderabad"
}
我正在尝试使用这个jQuery.merge(firstObject, secondObject)
,但它只需要两个参数所以我需要再次应用循环和交换对象,这是一个复杂的逻辑。有没有其他方法来合并这个?
答案 0 :(得分: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 :(得分:1)
我认为不能在一次通话中完成,所以试试
var obj = {};
$.each(arr, function (i, o) {
$.extend(obj, o)
})
console.log(obj)
演示:Fiddle
答案 2 :(得分: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]);
}