比较和添加/更新数组中的值

时间:2017-11-28 10:31:34

标签: javascript jquery json

如何通过比较现有数组在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]]
        }); 

    }   

});

1 个答案:

答案 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
    }

});