Delete all status from a json Twitter result if the key do not exist in a nested json in Javascript

50 Views Asked by At

From this Twitter result, i want to delete all entry/item/status who do not contain video in JavaScript.

It's mean that the extended_entities.media key will not exist. Obviously, it's also mean that the extended_entities.media.video_info.variants[0].url will not exist too.

Since i also want to use .map (or not) to rename all the key names.

I do not know how to delete the entire status if there's no video in this item.

Should i do this in two step? like deleting the item if there's no video then rename the result after with .map. Can it be done with filter, reduce, map, or foreach with some if and else in one shot or do .map after with the result?

The main key from Twitter is "statuses".The key for the video url will be renamed as "sources" later.

  var new_Data = data.statuses.map(function(item) {

    return {
      id: item.id,
      subtitle: item.text,
      //sources: keyExists(item.extended_entities, "url"),
      //sources: getMedia(keyExists(item.extended_entities, "variants"), item),
      sources: item.extended_entities.media.video_info.variants[0].url,
      //poster: item.entities?.media.id,
      tweetURL: "https://twitter.com/" + item.user.screen_name + "/status/" + item.id_str,
      name: item.user.name,
      username: item.user.screen_name,
      //retweet_count: item.retweeted_status.retweet_count,
      //favorite_count: item.retweeted_status.favorite_count,
      thumb: item.user.profile_image_url,
      userUrl: "https://twitter.com/" + item.user.screen_name
    };
 });

This .map example is the example i use to test for now but maybe 95% of these results do not contain video at all.

Here is a example of a Twitter API results: https://run.mocky.io/v3/30ca83f2-46f3-4c4a-9067-fcdabdcab75e You can search for .mp4 or extended_entities to help you find where they are. all item do not contains these key or value

1

There are 1 best solutions below

2
On

use reduce like this

  var new_Data = data.statuses.reduce(function (acc, item) {
    if (item.extended_entities?.media?.video_info?.variants?.[0].url) // AD YOUR CONDITION HERE
      acc.push({
        id: item.id,
        subtitle: item.text,
        //sources: keyExists(item.extended_entities, "url"),
        //sources: getMedia(keyExists(item.extended_entities, "variants"), item),
        sources: item.extended_entities.media.video_info.variants[0].url,
        //poster: item.entities?.media.id,
        tweetURL: "https://twitter.com/" + item.user.screen_name + "/status/" + item.id_str,
        name: item.user.name,
        username: item.user.screen_name,
        //retweet_count: item.retweeted_status.retweet_count,
        //favorite_count: item.retweeted_status.favorite_count,
        thumb: item.user.profile_image_url,
        userUrl: "https://twitter.com/" + item.user.screen_name,
      })
      return acc
  }, [])