使用jquery将json对象数组合并到单个对象中

时间:2014-01-07 10:17:52

标签: javascript jquery json

我有一个像这样的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),但它只需要两个参数所以我需要再次应用循环和交换对象,这是一个复杂的逻辑。有没有其他方法来合并这个?

3 个答案:

答案 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]);
}

Here is a working Fiddle