I am trying to normalize a dataset, update an array index, and then denormalize the data.
I'd like to change a P.O. at on a header line and have the change propagate to a linked order.
The data model is as follows:
let numSet = 0;
let numLine = 2;
let data = [
{
"order": {
"po_no": "original-po"
},
"items": [
{
"header": {
"po_no": "keep-this-value",
"set_no": 0
},
"line": {
"id": "A123",
"line_no": 1
}
},
{
"header": {
"po_no": "update-with-this-value",
"set_no": 0
},
"line": {
"id": "B234",
"line_no": 2
}
}
]
}
];
// The logic to normalize the data (appending the order data to each index), works as expected
let normalizedDataSet = [];
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i]['items'].length; j++) {
data[i]['items'][j]['order'] = data[i]['order']; // Set default header
normalizedDataSet.push(data[i]['items'][j]);
}
}
// The logic to update the normalized data, updating too many indices
for (i = 0; i < normalizedDataSet.length; i++) {
let index = normalizedDataSet[i];
if (numSet === index['header']['set_no'] && numLine === index['line']['line_no']) {
index['order']['po_no'] = index['header']['po_no'];
}
}
console.log(normalizedDataSet); // Expected output below
Expected output:
normalizedDataSet = [
{
"header": {
"po_no": 'keep-this-value',
"set_no": 0
},
"line": {
"id": 'A123',
"line_no": 1
},
"order": {
"po_no": 'original-po'
}
},
{
"header": {
"po_no": 'update-with-this-value',
"set_no": 0
},
"line": {
"id": 'B234',
"line_no": 2
},
"order": {
"po_no": 'update-with-this-value'
}
}
]
When logging line-by-line it seems to set correctly, but then there is a glitch when logging after the second for loop exits.
Once the data is updated I would like to resort it with the original schema.
The issue that I'm having is that the update logic is changing all entries with the same order, and is not just updating the single line. (i.e., it is updating (set_no = 0, line_no = 1) and (set_no = 0, line_no = 2), when it should only be updating the second case.
In this case, how would I update just the second index of the normalized data set?
po_noshould go, if anywhere.header po_noshould set theorder po_nowhen theset_noandline_nomatch the input.