0

I have a object from a Youtube api call, let's call it myObj I do a for loop and delete items I don't like with:

delete myObj.items[i]

the problem is it leaves "null" traces of items deleted this way, when i then log myObj again using JSON.stringify it looks like this:

myObj now is: {"kind":"youtube#SubscriptionListResponse","etag":"xxxxxxxxxxxxx","pageInfo":
{"totalResults":14,"resultsPerPage":30},"items":
[{"kind":"youtube#subscription","etag":"xxxxxx","id":"xxxxxxxxxx","snippet":{"publishedAt":"2020-12-
17T18:01:20.892352Z","title":"A Channel","description":"","resourceId":
{"kind":"youtube#channel","channelId":"xxxxx"},"channelId":"xxxxxx","thumbnails":{"default":
{"url":"xxxxxxxxxxxxxxxxxx"},"medium":{"url":"xxxxxxxxxxxxxxxxx"},"high":
{"url":"xxxxxxxxxxxxxxx"}}},"contentDetails":{"totalItemCount":17,"newItemCount":0,"activityType":"all"}}
,null,null,null,null,null,null,null,null,null,null,null,null,null]}

it works since it only keeps the "A Channel" item which is correct, but all the other items turn into null, and it's a problem for something like myObj.length later on.

I've read other threads about the issue, but they either reccomends using delete, which clearly doesn't work for my case, or splice (which doesn't work on my object from my understanding)

m4tt
  • 825
  • 1
  • 11
  • 28
  • 1
    Instead of changing the object, you could treat it like an immutable object and create a new object with or without the properties wanted/unwanted. This would also help, keeping a more functional approach. – FelHa Dec 19 '20 at 16:39
  • 2
    "*`splice` (which doesn't work on my object from my understanding)*" but you are manipulating the **array** which is at the property `items`. You can use `splice` on it. – VLAZ Dec 19 '20 at 16:39
  • i tried with myObj.items[i].splice(i,1) but it says splice is not a function – m4tt Dec 19 '20 at 16:45
  • 1
    Please go through this https://stackoverflow.com/questions/500606/deleting-array-elements-in-javascript-delete-vs-splice and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice – Nikhil Ponduri Dec 19 '20 at 16:48
  • 1
    @m4tt `myOb.items.splice(i, 1)` – Bergi Dec 19 '20 at 16:51
  • 1
    @m4tt you should be calling `.splice` on the *array*, not on an item in the array. – VLAZ Dec 19 '20 at 16:51
  • If you just need to remove the nulls, could filter this out: myObj.items.filter(item => item); – lortschi Dec 19 '20 at 16:54
  • thank you, i followed that first link and changed the loop to work in reverse, then using items.split instead of items[i] worked. btw i don't know who closed with duplicate, but that link doesn't mention to use reverse loop anywhere, so is not the solution for my case at all, maybe the first link pointed out by Nikhil is – m4tt Dec 19 '20 at 16:56

0 Answers0