0

How can I create a new JSON array in jquery with comparing existing array? if the array value exists then change the value or if new then push the new value

$(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]]
        }); 

    }   

});
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
vijay
  • 244
  • 4
  • 16
  • You do not need jQuery for this operation. Look into `Array.map`. Also, `Medicines` is not an array. Its a string – Rajesh Nov 28 '17 at 10:34
  • please post somewhere part of the `medicineOrderList` just to see what structure it has – Kresimir Pendic Nov 28 '17 at 10:35
  • you are looping on a string `Medicines` instead of an array . – Muhammad Omer Aslam Nov 28 '17 at 10:36
  • There is no JSON anywhere in your question. JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. Your "Json Arrays" are simply arrays. – T.J. Crowder Nov 28 '17 at 10:39
  • Medicines is a multi select array – vijay Nov 28 '17 at 10:48

1 Answers1

0

You can implements your own compare function

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;
}

and use it :

$(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
    }

});
Stéphane Ammar
  • 1,454
  • 10
  • 17