Suresh
Suresh

Reputation: 11

Append JSON objects

I have a JSON object array of the structure coming from server response like as sample

array1 ={
    "ID": "123",
    "Name": "John",
    "Age": "15"     
}
array2 ={
    "ID": "456",
    "Name": "Sue",
    "Age": "18"     
}

But now I want to append the both the array values in the following structure of

Expected Output:

{
    "Stud": [{
        "ID": "123",
        "Name": "John",
        "Age": "15"
    }, {
        "ID": "456",
        "Name": "Sue",
        "Age": "18"
    }]
}

Can anyone help to solve in the JavaScript language. Thanks for the Time to spend for request.

Upvotes: 0

Views: 78

Answers (3)

Agustin Dortona
Agustin Dortona

Reputation: 111

var obj1 ={
 "ID": "123",
 "Name": "John",
 "Age": "15"     
}
var obj2 ={
 "ID": "456",
 "Name": "Sue",
 "Age": "18"     
}

var obj3 = {
  "Stud": [obj1, obj2]
}

var objJSon = JSON.stringify(obj3);

To get the result as JSON

Upvotes: 0

Thomas
Thomas

Reputation: 845

array1 & array 2 are litteral objects not array ;)

You can solve your problem with

const array1 ={
     "ID": "123",
     "Name": "John",
     "Age": "15"     
};
const array2 ={
    "ID": "456",
    "Name": "Sue",
    "Age": "18"     
};

const stud = {
  Stud : [array1, array2]
};

If you have N array you can use Array.prototype.concat

Upvotes: 1

Shudrum
Shudrum

Reputation: 176

var array1 ={
    "ID": "123",
    "Name": "John",
    "Age": "15"     
}
var array2 ={
    "ID": "456",
    "Name": "Sue",
    "Age": "18"     
}

var Output = {
  "Stud": [array1, array2]
}

Upvotes: 1

Related Questions