I have an object array with the following structure:
[
{
"id": 1,
"uid": "card-vwy733s3rC",
"body": {
"text": "Test"
},
"type": 0,
"button": [
{
"uid": "button-tFDHsmExnx",
"title": "Get Started",
"event": [
{
"id": 2,
"action": 5,
"value": "https://en.wikipedia.org/wiki/Educational_technology"
},
{
"id": 2,
"action": 5,
"value": "https://en.wikipedia.org/wiki/Educational_technology"
}
],
"isEnabled": true
}
],
"audio": {
"uid": "audio-NVBK0U6BXE",
"url": "https://s3.eu-west-2.amazonaws.com/media.testing.co.uk/default/testing_startup_ideas.mp3"
}
}
]
I would like to re-index the value at button -> event -> id on occasion, provided the topmost uid matches. This means that the two 2's become 1 and 2. However, when I run my method below, it doesn't work, and it returns an identical id's for all the items in the button -> event array:
static resetCourseContentButtonEventIndexes(
courseContent: ICourseContent[],
selectedCourseContentUid: string
): ICourseContent[] {
for (let i = 0; i < courseContent.length; i++) {
if (courseContent[i].uid === selectedCourseContentUid) {
for (let j = 0; j < courseContent[i].button.length; j++) {
for (let k = 0; k < courseContent[i].button[j].event.length; k++) {
courseContent[i].button[j].event[k].id = k + 1;
}
}
}
}
return courseContent;
}
I'm confused about why this is happening, how can I fix it?
I call it from another method:
static cloneCourseContentButtonEventByIndex(
courseContent: ICourseContent[],
selectedCourseContentUid: string,
selectedCourseElementUid: string,
courseContentButtonEventIndex: number
) {
for (let i = 0; i < courseContent.length; i++) {
if (courseContent[i].uid === selectedCourseContentUid) {
for (let j = 0; j < courseContent[i].button.length; j++) {
if (courseContent[i].button[j].uid === selectedCourseElementUid) {
courseContent[i].button[j].event.push(
courseContent[i].button[j].event[courseContentButtonEventIndex]
);
}
}
}
}
return JSON.parse(
JSON.stringify(
this.resetCourseContentButtonEventIndexes(courseContent, selectedCourseContentUid)
)
);
}
resetCourseContentButtonEventIndexescourseContent[i].button[j].event.push(courseContent[i].button[j].event[courseContentButtonEventIndex]);, instead clone the object as you pushcourseContent[i].button[j].event.push({...courseContent[i].button[j].event[courseContentButtonEventIndex]});