The class dictionary implemented by JavaScript inserts or updates method instances


This article illustrates the JavaScript implementation of the class dictionary insert or update method. Share to everybody for everybody reference. The details are as follows:

Code expressed the class dictionary insert or update related ideas, interested friends mainly understand the meaning of the code on the line, not too deep

<script type="text/javascript">
  function insertOrUpdate(array, keyName, keyVal, fieldNames, fieldVals) {
  var hasExist = false;
  var len = array.length;
  for (var i = 0; i < len; i++) {
   if (array[i][keyName] && array[i][keyName] == keyVal) {
   //  Existing updates directly
   hasExist = true;
   for (var j = 0; j < fieldNames.length; j++) {
    array[i][fieldNames[j]] = fieldVals[j];
   }
   }
  }
  if (!hasExist) {//  Insert if none exists
   array[len] = {};
   array[len][keyName] = keyVal;
   for (var k = 0; k < fieldNames.length; k++) {
   array[len][fieldNames[k]] = fieldVals[k];
   }
  }
  }
  var orders = [
    {
    "OrderId" : 1,
    "OrderAmount" : {
     "OldValue" : 10,
     "NewValue" : 20
    }
    },
    {
    "OrderId" : 2,
    "OrderAmount" : {
     "OldValue" : 20,
     "NewValue" : 30
    }
    }];
  insertOrUpdate(orders, "OrderId", 1, ["OrderAmount"], [{"OldValue": 145, "NewValue": 1125}]);
  console.dir(orders);
  insertOrUpdate(orders, "OrderId", 3, ["OrderAmount"], [{"OldValue": 75, "NewValue": 95}]);
  console.dir(orders);
</script>

Hopefully, this article has been helpful in your javascript programming.