javascript - How to extract multiple hashtags from a JSON object? -
i trying extract "animal" , "fish" hashtags json object below. know how extract first instance named "animal", have no idea how extract both instances. thinking use loop, unsure start it. please advise.
data = '{"hashtags":[{"text":"animal","indices":[5110,1521]}, {"text":"fish","indices":[122,142]}],"symbols":[],"user_mentions": [{"screen_name":"test241","name":"test dude","id":4999095,"id_str":"489996095","indices":[30,1111]}, {"screen_name":"test","name":"test","id":11999991, "id_str":"1999990", "indices":[11,11]}],"urls":[]}'; function showhashtag(data){ = 0; obj = json.parse(data); console.log(obj.hashtags[i].text); } showhashtag(data);
let data = '{"hashtags":[{"text":"animal","indices":[5110,1521]},{"text":"fish","indices":[122,142]}],"symbols":[],"user_mentions":[{"screen_name":"test241","name":"test dude","id":4999095,"id_str":"489996095","indices":[30,1111]}, {"screen_name":"test","name":"test","id":11999991, "id_str":"1999990", "indices":[11,11]}],"urls":[]}'; function showhashtag(data){ return json.parse(data).hashtags.filter(e => /animal|fish/i.test(e.text)) } console.log(showhashtag(data));
to make function reusable, in case want find other "hashtags", pass array so:
function showhashtag(data, tags){ let r = new regexp(tags.join("|"), "i"); return json.parse(data).hashtags.filter(e => r.test(e.text)) } console.log(showhashtag(data, ['animal', 'fish']));
to text property, chain map()
console.log(showhashtag(data, ['animal', 'fish']).map(e => e.text));
or in function
return json.parse(data).hashtags .filter(e => /animal|fish/i.test(e.text)) .map(e => e.text);
edit:
i don't why filter animal , fish if want array ['animal', 'fish']
. objects have text property, again, use filter,
let data = '{"hashtags":[{"text":"animal","indices":[5110,1521]},{"text":"fish","indices":[122,142]}],"symbols":[],"user_mentions":[{"screen_name":"test241","name":"test dude","id":4999095,"id_str":"489996095","indices":[30,1111]}, {"screen_name":"test","name":"test","id":11999991, "id_str":"1999990", "indices":[11,11]}],"urls":[]}'; function showhashtag(data){ return json.parse(data).hashtags .filter(e => e.text) .map(e => e.text); } console.log(showhashtag(data));
Comments
Post a Comment