skip to Main Content

I am working with the Twitter API for trends (see: https://developer.twitter.com/en/docs/trends/trends-for-location/api-reference/get-trends-place).

The API returns the following JSON:

{
  trends: [
    {
      name: 'Boris',
      url: 'http://twitter.com/search?q=Boris',
      promoted_content: null,
      query: 'Boris',
      tweet_volume: 1083274
    },
    {
      name: '#COVID19',
      url: 'http://twitter.com/search?q=%23COVID19',
      promoted_content: null,
      query: '%23COVID19',
      tweet_volume: 2088454
    },
    {
      name: '#WorldHealthDay',
      url: 'http://twitter.com/search?q=%23WorldHealthDay',
      promoted_content: null,
      query: '%23WorldHealthDay',
      tweet_volume: 250817
    }
  ],
  as_of: '2020-04-07T14:06:49Z',
  created_at: '2020-04-07T14:03:32Z',
  locations: [ { name: 'London', woeid: 44418 } ]
}

I would like to transform this into a Javascript array containing all of the values where the key is name; ie.:

arr=["Boris", "#COVID19", "WorldHealthDay"]

How can I achieve this? From what I have read, native JavaScript JSON parsers cannot handle duplicate keys.

2

Answers


  1. Arrays can contain duplicate VALUES, which is what you’ve requested. Arrays do not contain keys, and these strings in the array are also values of the ‘name’ key inside of the JSON returned from the twitter API.

    To solve your problem, for example, with a very basic iteration and no Array.map

    const data = JSON.parse(data_str);
    const arr = [];
    for (const trend of data.trends) {
        arr.push(trend.name);
    }
    
    Login or Signup to reply.
  2. your data:

    trends = [
        {
          name: 'Boris',
          url: 'http://twitter.com/search?q=Boris',
          promoted_content: null,
          query: 'Boris',
          tweet_volume: 1083274
        },
        {
          name: '#COVID19',
          url: 'http://twitter.com/search?q=%23COVID19',
          promoted_content: null,
          query: '%23COVID19',
          tweet_volume: 2088454
        },
        {
          name: '#WorldHealthDay',
          url: 'http://twitter.com/search?q=%23WorldHealthDay',
          promoted_content: null,
          query: '%23WorldHealthDay',
          tweet_volume: 250817
        }
      ];
    

    then use map

    var ans = trends.map(d => d.name)
    

    results:

     ans = ["Boris", "#COVID19", "#WorldHealthDay"]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search