I am trying to "push" information inside the object based on certain conditions.
I need to insert/push/assign more information within the property "materials" but I am not sure how to do this.
This is the structure of my current object:
const MYOBJECT = {
"status": "Work",
"present": true,
"materials": [
{
"link1": {
"url": "www.google.com",
}
},
{
"driveFile": {
"driveFile": {
"id": "xyz123456fghtfsdag"
},
"shareMode": "VIEW"
}
},
],
"dueDate": {
"day": resource.date_day,
"month": resource.date_month,
"year": resource.date_year
},
}
I am trying to add/push, if a condition is met, the variables shown below ("additional1" & "additional2") inside the object property "materials" without replacing/deleting any other information within the object:
var additional1 = { "link2": { "url": "www.yahoo.com", } }
var additional2 = { "link3": { "url": "www.bing.com", } }
I am looking for the END result to look like this (assuming the "if statements" / conditions are met):
const MYOBJECT = {
"status": "Work",
"present": true,
"materials": [
{
"link1": {
"url": "www.google.com",
}
},
// Insert variable addition1
{
"link2": {
"url": "www.yahoo.com",
}
},
// Insert variable addition2
{
"link3": {
"url": "www.bing.com",
}
},
{
"driveFile": {
"driveFile": {
"id": "xyz123456fghtfsdag"
},
"shareMode": "VIEW"
}
},
],
"dueDate": {
"day": resource.date_day,
"month": resource.date_month,
"year": resource.date_year
},
}
materials
is an array, so you can add new members there using the push() method.
The end result would look something like this:
if (conditionIsMet) {
MYOBJECT.materials.push(additional);
}
Please note, that the push() method adds element to the end of the array, so if you want your results to reside in the middle of the array (like you did in your example) you'll need to specify additional logic for this.