0

I am having array of objects defined in javascript and would like to delete values based on object property.

I used below code :

     var addedItems = [];
     var item = {};
     item["TId"] = "";
     item["VNo"] = "";
     item["IDate"] = "";
     item["Rate"] = 22;
     item["ItemId"] = 12;
     item["Quantity"] = 1;
     item["ItemTypeId"] = 3;
     addedItems.push(item);

     removeValueFromObjectByValue(addedItems,12);


     function removeValueFromObjectByValue(jsonObject, value) {
        jQuery.each(jsonObject, function (i, val) {
            if (val.ItemId == value) // delete index
            {
                return;
                delete jsonObject[i];
                return;
            }
        });
    }

Expected Result : When I remove value, it should give me array with 0 elements.

Actual output : When I remove value, I am getting array with 1 element and the element value is null.

Manthan Devani
  • 179
  • 2
  • 4

1 Answers1

0

You can use Object.values and splice. Inside the function create a new copy of the original array using JSON.parse & JSON.stringify so that original array does not get modified. Inside the forEach callback use Object.values which will give an array of values. Then use includes to check if this array created using Object.values contains the parameter passed in the function. If true then remove the element from the copied array using splice

var addedItems = [];
var item = {};
item["TId"] = "";
item["VNo"] = "";
item["IDate"] = "";
item["Rate"] = 22;
item["ItemId"] = 12;
item["Quantity"] = 1;
item["ItemTypeId"] = 3;
addedItems.push(item);

function removeValueFromObjectByValue(arr, num) {
  let newArr = JSON.parse(JSON.stringify(arr))
  arr.forEach(function(item, index) {
    let isNumPresent = Object.values(item).includes(num)
    if (isNumPresent) {
      newArr.splice(index, 1);
    }
  })
  return newArr;
}
console.log(removeValueFromObjectByValue(addedItems, 12));
brk
  • 48,835
  • 10
  • 56
  • 78