I am trying to update a specific array index with a new carrier_id
and name
.
However, I'm getting a puzzling assignment problem.
Comment line with Note #1
out and nData will look fine, otherwise its order property appears to get set before updateNormalizedData is called.
let data = JSON.parse('[{"order":{"po_no":"po_2019","ship_details":{"carrier_id":1044777,"method":"FREE Shipping"},"sub_total":0},"items":[{"header":{"set_no":0,"carrier_id":104777,"po_no":"po_2019"},"line":{"item_id":"ABC RE1000","line_no":0}},{"header":{"set_no":0,"carrier_id":104777,"po_no":"po_2019"},"line":{"item_id":"ABC DA1111","line_no":1}}]}]');
let numSet = 0;
let numLine = 1;
let args = {"carrier_id": 555111};
function normalizeData(data, numSet, numLine, args) {
let i = 0, j = 0, l = data.length;
let normalizedDataSet = [];
// console.log(data[i])
for (i = 0; i < l; i++) {
let m = data[i]['items'].length;
for (j = 0; j < m; j++) {
data[i]['items'][j]['order'] = { ...data[i]['order'] }; // Destructure data to assign value, not object reference
normalizedDataSet.push(data[i]['items'][j]);
}
}
// console.log('nData', normalizedDataSet);
updateNormalizedData(normalizedDataSet, numSet, numLine, args); // Note #1
}
function updateNormalizedData(normalizedDataSet, numSet, numLine, args) {
let i;
let n = normalizedDataSet.length;
let newNormal = [];
for (i = 0; i < n; i++) {
let index = { ...normalizedDataSet };
if (numSet === index[i]['header']['set_no'] && numLine === index[i]['line']['line_no']) {
let shipMethods = JSON.parse('[{"id":103366,"name":"FREE Shipping"},{"id":200200,"name":"BEST"},{"id":555111,"name":"COLLECT"}]');
let shipMethod = shipMethods.filter(item => { return item.id === args.carrier_id }); // [0]['name'];
console.log("date_updated this index", i);
index[i]['order']['ship_details']['carrier_id'] = args.carrier_id;
index[i]['order']['ship_details']['method'] = shipMethod[0]['name'];
newNormal.push(index[i]); // Should update order.ship_details.carrier_id
} else {
console.log("Use original index");
newNormal.push(normalizedDataSet[i]); // Should NOT update order.ship_details.carrier_id
}
}
console.log('new normal', JSON.stringify(newNormal));
}
normalizeData(data, numSet, numLine, args);
I'm not sure how the property is getting assigned "before" a function is called that assigns it.
I'm guessing it may have something to do with the data destructuring, but I'm not certain.
Any guidance / help is greatly appreciated.
In this example I'm trying to update just { "setNo": 0, "lineNo": 1 }
with new normal order data, but both lines 0 and 1 are being set.