Use Spread syntax to add a JSON object to another JSON object in JavaScript. And use the push() method to add a JSON array at end of an array.
let combined = { …obj1, …obj2 };
Or if the JSON array
obj.push(myObj);
Add JSON object to another JSON object in JavaScript
Simple example code uses the object spread syntax:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
const original = {
"product": {
"prodId": "PROD100"
},
"pkgs": {
"pkgId": "PKG137"
},
"discount": "50",
"pFrom": null,
"pTo": null,
"amt": "599",
"isActive": "false"
}
const toAppend = {
"customer": {
"custId": "CUST1002"
},
}
const newJSON = { ...toAppend, ...original };
console.log(newJSON);
</script>
</body>
</html>
Output:
Add json object to JSON Array
<script type="text/javascript">
favorites = [{
"artist" : "ABC",
"song_name" : "Mild"
}];
var myObj = {
"artist" : "XYZ",
"song_name" : "Rock"
};
favorites.push(myObj);
console.log(favorites);
</script>
Output:
How do I add JSON objects as a new level to another JSON object?
Answer: code that gets in the end collection of two JSON objects, something like this.
var jsonL1 = {"holder1": {}}
var jsonL2 = {"section":"0 6","date":"11/12/13"}
Just do this
L1.holder1 = L2
Do comment if you have any doubts or suggestions on this Js JSON topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version
hi,
I need to club the below
var jsonObject1={
“Item1”:{
}
}
var jsonObject2={
“Item2”:{
}
}
var jsonObject3= need to append jsonObject1 and jsonObject2
I expect
jsonObject3={
“Item1”:{
},
“Item2”:{
}
}
Appreciate your help.