I am working on this project part that creates an object based on the template and pushes it to an array and will run based on the amount of line items I have. There is a tag HL that is a hierarchal loop the first element in that tags element array needs to change depending on how many hierarchal loops are created. The issue is that when I update the array of elements elements[0] = hlcount;
it updates the other object in the obj array. (sorry I am bad at explaining this) Please see code and output and expected output.
What am I doing wrong here?
let hlcount = 1;
function hl_I(hl){
//console.log(maps);
for(x in hl){
let tag = x;
let elements = hl[x]
if( tag == "HL"){
console.log(hlcount);
elements[0] = hlcount;
}
//console.log(tag + elements);
obj.push({"tag":tag, "elements":elements});
}
hlcount++;
}
let hlp = map.structure.HL_P;
let hli = map.structure.HL_I;
for(l in translation.LineItem){
hl_I(hlp);
hl_I(hli);
}
console.log(obj);
Output:
1
2
3
4
[
{ tag: 'HL', elements: [ 3, '2', 'P' ] },
{ tag: 'MAN', elements: [ 'CP', '1ZT912T80392186383' ] },
{ tag: 'HL', elements: [ 4, '3', 'I' ] },
{ tag: 'LIN', elements: [ '1', 'SK', '{sku}' ] },
{ tag: 'SN1', elements: [ ',', 'qty', 'EA' ] },
{ tag: 'PID', elements: [ 'F', '08', '', '', 'CFMT160-BRONZE' ] },
{ tag: 'N1', elements: [ 'CT', 'United States' ] },
{ tag: 'N4', elements: [ '', '', '', 'USA' ] },
{ tag: 'HL', elements: [ 3, '2', 'P' ] },
{ tag: 'MAN', elements: [ 'CP', '1ZT912T80392186383' ] },
{ tag: 'HL', elements: [ 4, '3', 'I' ] },
{ tag: 'LIN', elements: [ '1', 'SK', '{sku}' ] },
{ tag: 'SN1', elements: [ ',', 'qty', 'EA' ] },
{ tag: 'PID', elements: [ 'F', '08', '', '', 'CFMT160-BRONZE' ] },
{ tag: 'N1', elements: [ 'CT', 'United States' ] },
{ tag: 'N4', elements: [ '', '', '', 'USA' ] }
]
Expected output:
1
2
3
4
[
{ tag: 'HL', elements: [ 1, '2', 'P' ] },
{ tag: 'MAN', elements: [ 'CP', '1ZT912T80392186383' ] },
{ tag: 'HL', elements: [ 2, '3', 'I' ] },
{ tag: 'LIN', elements: [ '1', 'SK', '{sku}' ] },
{ tag: 'SN1', elements: [ ',', 'qty', 'EA' ] },
{ tag: 'PID', elements: [ 'F', '08', '', '', 'CFMT160-BRONZE' ] },
{ tag: 'N1', elements: [ 'CT', 'United States' ] },
{ tag: 'N4', elements: [ '', '', '', 'USA' ] },
{ tag: 'HL', elements: [ 3, '2', 'P' ] },
{ tag: 'MAN', elements: [ 'CP', '1ZT912T80392186383' ] },
{ tag: 'HL', elements: [ 4, '3', 'I' ] },
{ tag: 'LIN', elements: [ '1', 'SK', '{sku}' ] },
{ tag: 'SN1', elements: [ ',', 'qty', 'EA' ] },
{ tag: 'PID', elements: [ 'F', '08', '', '', 'CFMT160-BRONZE' ] },
{ tag: 'N1', elements: [ 'CT', 'United States' ] },
{ tag: 'N4', elements: [ '', '', '', 'USA' ] }
]