I am scratching my head on making assignments to 2 dim object array by re-using previously set objects (Angular/Typescript). My result shows that the last assignment overrides the previous two and I cannot figure out why. Can you please have a look at what I am missing?
export interface Criteria {
fieldValue: any;
fieldName: string;
childItems?: Criteria[];
}
// function to build my array of objects:
setCriteria() {
// parent object 1
// to be reused / reassigned to array below
const criteriaLevel1: Criteria = {
fieldName: 'Criteria name',
fieldValue: 'Crit-Level-1',
childItems: []
};
// parent object 2 - child of object 1
// to be reused / reassigned to array below
// into - childItems[0]
const criteriaLevel2: Criteria = {
fieldName: 'Criteria name',
fieldValue: 'Crit-Level-2',
childItems: []
};
// list of 3 different items to be assigned to array
// into - childItems[0].childItems[0] of each array record.
const itemsABC: string[] = [
'item AAA',
'item BBB',
'item CCC'
];
const criteriaArray = [];
let ix = 0;
itemsABC.forEach(item => {
console.log('item: ' + item);
criteriaArray[ix] = [];
criteriaArray[ix][0] = criteriaLevel1;
criteriaArray[ix][0].childItems[0] = criteriaLevel2;
criteriaArray[ix][0].childItems[0].childItems[0] = {
fieldName: 'name',
fieldValue: item + '-' + ix
};
ix++;
});
// output test
for (let i = 0; i < 3; i++) {
console.log('ix: ' + i);
for (const itemA of criteriaArray[i]) {
console.log('a: ' + itemA.fieldName + ' - ' + itemA.fieldValue);
for (const itemB of itemA.childItems) {
console.log('b: ' + itemB.fieldName + ' - ' + itemB.fieldValue);
for (const itemC of itemB.childItems) {
console.log('c: ' + itemC.fieldName + ' - ' + itemC.fieldValue);
}
}
}
}
}
I get this output:
index: 0 - inserting item: item AAA
index: 1 - inserting item: item BBB
index: 2 - inserting item: item CCC
ix: 0
a: Criteria name - Crit-Level-1
b: Criteria name - Crit-Level-2
c: name - item CCC-2 // BUT I am expecting here: item AAA-0
ix: 1
a: Criteria name - Crit-Level-1
b: Criteria name - Crit-Level-2
c: name - item CCC-2 // BUT I am expecting here: item BBB-1
ix: 2
a: Criteria name - Crit-Level-1
b: Criteria name - Crit-Level-2
c: name - item CCC-2 // YES as expected here: item CCC-2
What am I doing wrong ?