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
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
your data:
then use map
results: