String array with key and value Remove already exist

43
August 20, 2019, at 11:20 AM

I found some similar questions, but none helped me.

I have an array, and I am pushing items into it. I want to check if there is already an item then removes and add a new value.

I am doing this in the success of an ajax call,

var taxSplitUp = []; // my array
// ajax call here, in the success 
for (var i in data.d) { 
  var ItemTaxAmt= data.d[i].ItemTaxAmt;
  var TaxName = data.d[i].TaxName;
  var idx = $.inArray(TaxName, taxSplitUp); // checks if already exist
  if (idx == -1) {
    var tx1 = '{"' + TaxName + '":"' + parseFloat(ItemTaxAmt).toFixed(2) + '"}';
    taxSplitUp.push(tx1);
  } 
  else {
    taxSplitUp.splice(idx, 1); // removing
    var t1 = taxSplitUp[TaxName]; // selecting the value from array
    var tx1 = '{"' + TaxName + '":"' + parseFloat(ItemTaxAmt).toFixed(2) + parseFloat(t1).toFixed(2) + '"}';
    taxSplitUp.push(tx1);
  }
}

Here if the same key came, then I want to add the values together and want only one in the array, but the checking always returns false and adds another into the array.

please help.

Answer 1

$.inArray wont work with associative array. Try below solution

for (var i in data) {
  var ItemTaxAmt= data[i].ItemTaxAmt;
  var TaxName = data[i].TaxName;
  console.log(TaxName);
  $.map(taxSplitUp, function(item, index) {
 if (item.TaxName == TaxName) {
   item.ItemTaxAmt = ItemTaxAmt;
 }else{
    taxSplitUp.push({
        'TaxName' :TaxName,
        'ItemTaxAmt' : ItemTaxAmt
    });
 }
});
}
console.log(taxSplitUp);
READ ALSO
Basic Angular Components not Displaying in Browser [duplicate]

Basic Angular Components not Displaying in Browser [duplicate]

This question already has an answer here:

57
Push Notification Using Amazon SNS (Node)

Push Notification Using Amazon SNS (Node)

I am trying to implement push notification using Amazon SNS in NodeI have created a topic and published a message using below code

37
winston logging only working in callbacks not working in catch blocks

winston logging only working in callbacks not working in catch blocks

I am setting up a server and want to log every errors and information in my custom filesall those errors which are caught in catch block should be store in "catch_error

15