Kevin Daniel
Kevin Daniel

Reputation: 51

Removing empty array values on multidimensional array

I want to remove arrays cctype, cctypologycode, and amount when they are empty from array. best way to do it ?

{
  "ccInput": [
    {
      "designSummaryId": 6,
      "CCType": "A",
      "CCTypologyCode": "A",
      "Amount": "1"
    },
    {
      "designSummaryId": 7,
      "CCType": "",
      "CCTypologyCode": "",
      "Amount": ""
    },
  ]
}

ccInput[1] should be removed from the array

Upvotes: 0

Views: 249

Answers (2)

gomalley411
gomalley411

Reputation: 1

I don't know much about TypeScript, but I do know you can set the array to []. However, for those of you looking to get rid of only part of an array but not all of it, the simplest way to do so that I know of is to just set each value to 0 for numbers, '' for characters, "" for Strings, etc.

Upvotes: 0

jo_va
jo_va

Reputation: 13964

If you want to remove some objects from your array, use Array.prototytpe.filter().

You can do it in an immutable way by copying each property of your object using the spread operator and then filter the ccInput property:

const obj = {ccInput:[{designSummaryId:6,CCType:"A",CCTypologyCode:"A",Amount:"1"},{designSummaryId:7,CCType:"",CCTypologyCode:"",Amount:""}]};

const result = { ...obj, ccInput: obj.ccInput.filter(x => x.CCType && x.CCTypologyCode) };

console.log(result);

Or if you want to modify your object in place, simply reassign the ccInput property:

const obj = {ccInput:[{designSummaryId:6,CCType:"A",CCTypologyCode:"A",Amount:"1"},{designSummaryId:7,CCType:"",CCTypologyCode:"",Amount:""}]};

obj.ccInput = obj.ccInput.filter(x => x.CCType && x.CCTypologyCode);

console.log(obj);

Upvotes: 2

Related Questions