I have an array of shipments and I am running a loop on the array to find shipments which have more than one package so I can clone them within in a new array. I need to process shipping labels which produce one label per object in the array.
I have added a new key/value pair to show the individual package number from a counter but all my "BAG INDEX" are coming to the same number
// Function to sort the concatenated array
function compare( a, b ) {
if ( a["SNAP ID"] < b["SNAP ID"] ){
return -1;
}
if ( a["SNAP ID"] > b["SNAP ID"] ){
return 1;
}
return 0;
}
// Demo shipments array
var shipments = [{
"SNAP ID": "1234567890",
"FULL NAME": "Person 1",
"PACKAGE QTY": 5
},
{
"SNAP ID": "0987654321",
"FULL NAME": "Person 2",
"PACKAGE QTY": 2
},
{
"SNAP ID": "5432167890",
"FULL NAME": "Person 3",
"PACKAGE QTY": 3
}
];
// Empty array which will contain cloned shipment objects
var data = [];
// Running loop on the shipments array
for (var i = 0; i < shipments.length; i++) {
var Pkg = shipments[i]["PACKAGE QTY"]
var shipment = shipments[i]
shipment["BAG INDEX"] = 1
// Running loop on the shipments containing more the 1 packages
if (Pkg > 1) {
for (var k = 0; k < (Pkg - 1); k++) {
data.push(shipment);
shipment["BAG INDEX"] += 1;
};
};
};
var complete = shipments.concat(data);
var sorted = complete.sort(compare);
console.log(sorted);
This is what I am getting back
0: {SNAP ID: "0987654321", FULL NAME: "Person 2", PACKAGE QTY: 2, BAG INDEX: 2}
1: {SNAP ID: "0987654321", FULL NAME: "Person 2", PACKAGE QTY: 2, BAG INDEX: 2}
2: {SNAP ID: "1234567890", FULL NAME: "Person 1", PACKAGE QTY: 5, BAG INDEX: 5}
3: {SNAP ID: "1234567890", FULL NAME: "Person 1", PACKAGE QTY: 5, BAG INDEX: 5}
4: {SNAP ID: "1234567890", FULL NAME: "Person 1", PACKAGE QTY: 5, BAG INDEX: 5}
5: {SNAP ID: "1234567890", FULL NAME: "Person 1", PACKAGE QTY: 5, BAG INDEX: 5}
6: {SNAP ID: "1234567890", FULL NAME: "Person 1", PACKAGE QTY: 5, BAG INDEX: 5}
7: {SNAP ID: "5432167890", FULL NAME: "Person 3", PACKAGE QTY: 3, BAG INDEX: 3}
8: {SNAP ID: "5432167890", FULL NAME: "Person 3", PACKAGE QTY: 3, BAG INDEX: 3}
9: {SNAP ID: "5432167890", FULL NAME: "Person 3", PACKAGE QTY: 3, BAG INDEX: 3}
length: 10
You have to create a copy of your object. Otherwise you will increase the BAG INDEX
for the objects you already added to your data
array as well.
Simply use:
data.push(Object.assign({}, shipment));
You need to create a new object in here:
if (Pkg > 1) {
for (var k = 0; k < (Pkg - 1); k++) {
data.push(shipment);
shipment["BAG INDEX"] += 1;
};
};
Otherwise you're just operating on the same shipment object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.