我正在尝试使用新的carrier_id
和name
更新特定的数组索引。
但是,我遇到了一个令人困惑的作业问题。
注释行中有Note #1
且nData看起来很好,否则它的order属性在调用updateNormalizedData之前似乎已设置。
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);
我不确定如何在调用分配该属性的函数之前分配该属性。
我猜可能与数据解构有关,但我不确定。
非常感谢任何指导/帮助。
在此示例中,我尝试仅使用新的正常订单数据更新{ "setNo": 0, "lineNo": 1 }
,但同时设置了第0行和第1行。