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??

1
  • @GeorgeStocker there could be other duplicates but the one marked here is about creating a new array Commented Jan 7, 2014 at 10:23

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Sir thank you. you helped me second time. +1 for you.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.