-2

I have following JSON,

[
   {
      "Id":163,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service50031"
   },
   {
      "Id":161,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service50029"
   },
   {
      "Id":160,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service50028"
   },
   {
      "Id":159,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service50027"
   }
]

If I pass 163, I need to remove that node from the JSON, my expected output is,

[
   {
      "Id":161,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service50029"
   },
   {
      "Id":160,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service50028"
   },
   {
      "Id":159,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service50027"
   }
]

AS well as I need to insert item to the JSON, if I pass following

   {
      "Id":164,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service8000"
   }

I need following JSOn output,

[
   {
      "Id":164,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service8000"
   },
   {
      "Id":163,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service50031"
   },
   {
      "Id":161,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service50029"
   },
   {
      "Id":160,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service50028"
   },
   {
      "Id":159,
      "CategoryId":"8",
      "ServiceTypeId":"2",
      "ServiceName":"Service50027"
   }
]

How can I do this?

thomsan
  • 433
  • 5
  • 19
  • Does this answer your question? [Remove Object from Array using JavaScript](https://stackoverflow.com/questions/10024866/remove-object-from-array-using-javascript) – Billy Brown Sep 02 '20 at 09:21

1 Answers1

1

const data = [
  {Id:163,CategoryId:"8",ServiceTypeId:"2",ServiceName:"Service50031"},
  {Id:161,CategoryId:"8",ServiceTypeId:"2",ServiceName:"Service50029"},
  {Id:160,CategoryId:"8",ServiceTypeId:"2",ServiceName:"Service50028"},
  {Id:159,CategoryId:"8",ServiceTypeId:"2",ServiceName:"Service50027"}
];

const removeRecordById = (arr, Id) => {
  const i = arr.findIndex(a => a.Id == Id);
  if (i > -1) arr.splice(i, 1);
};


removeRecordById(data, 163);
console.log(data);
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313