如何通过比较现有数组在jquery中创建新的JSON
数组?如果数组值存在则更改值,如果为new,则按下新值
$(document).on('change','#orderedMedicines',function(){
Medicines=$('#orderedMedicines').val(); /* Multiple Select Array */
medicineOrderList /* Existing Json Array */
/* [{medicineName: "medicine1 ", quantity: 5, stock: "50.00"},{medicineName: "medicine2 ", quantity: 10, stock: "50.00"}] */
var newMedicineOrderList=[]; /* New Json Array */
for(var i=0;i<Medicines.length;i++){
/* Push into new array but check with exist array if duplicates medicineName then want to get this stock and push instead of 0 in new array */
newMedicineOrderList.push({
medicineName: medicineWithUnits[Medicines[i]],
quantity: 0,
stock:medicineWithStock[Medicines[i]]
});
}
});
答案 0 :(得分:0)
您可以实现自己的比较功能
function indexOfMedecine(o,arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].x == o.medicineName && arr[i].quantity == o.quantity && arr[i].stock == o.stock) {
return i;
}
}
return -1;
}
并使用它:
$(document).on('change', '#orderedMedicines', function() {
Medicines = $('#orderedMedicines').val(); /* Multiple Select Array */
medicineOrderList /* Existing Json Array */
var newMedicineOrderList=[]; /* New Json Array */
for(var i=0;i<Medicines.length;i++){
/* Push into new array but check with exist array if duplicates medicineName then want to get this stock and push instead of 0 in new array */
var newMed = {
medicineName: medicineWithUnits[Medicines[i]],
quantity: 0,
stock:medicineWithStock[Medicines[i]]
}
if(indexOfMedecine(newMed,newMedicineOrderList) < 0){
newMedicineOrderList.push(newMed);
} else {
//do your stuff
}
});