0

I have an array of json objects like these which looks like this

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

Now what I am trying to do is combining the whole array into single json object

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

I am trying with this jQuery.merge(firstObject, secondObject)but it takes only two arguments So again I need to apply loop and swapping the objects and so a complex logic. Is there any other way to merge this??

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126

3 Answers3

3

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 Fiddle: http://jsfiddle.net/wVGah/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
2

I don't think it can be done in a single call so try

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

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Use jQuery .extend function like this:

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

Igl3
  • 4,900
  • 5
  • 35
  • 69