Having the JSON Array provided below, my current challenge is in adding a new object to one of the array elements. The issue arises when attempting to push a new object into the array array1
at index 0
of arrayHolder
, as it leads to all existing array1
elements being updated with the new object.
{
"arrayHolder": [
{
"array1": [],
"array2": [],
"array3": [],
"array4": []
},
{
"array1": [],
"array2": [],
"array3": [],
"array4": []
},
{
"array1": [],
"array2": [],
"array3": [],
"array4": []
},
{
"array1": [],
"array2": [],
"array3": [],
"array4": []
}
]
}
The code snippet below demonstrates how I am currently pushing to array1
:
var jsonStr = "{\"arrayHolder\":[{\"array1\": [],\"....."; // Represents the Json String
var jsonObj = JSON.parse(jsonStr); // Convert string to an object
var newObj = {"value": 1}; // New object meant to be pushed
jsonObj.arrayHolder[0].array1.push(newObj);
// A similar approach yields similar results
jsonObj.arrayHolder[0]["array1"][0] = newObj;
The resulting output shows:
{
"arrayHolder": [
{
"array1": [{"value": 1}],
"array2": [],
"array3": [],
"array4": []
},
{
"array1": [{"value": 1}],
"array2": [],
"array3": [],
"array4": []
},
{
"array1": [{"value": 1}],
"array2": [],
"array3": [],
"array4": []
},
{
"array1": [{"value": 1}],
"array2": [],
"array3": [],
"array4": []
}
]
}
The desired outcome is to update the value of array1
solely for the element at index 0
within the arrayHolder
array, while leaving the other array1
elements untouched in the main array.