0

I am using google trends API to eventually export trends data to an excel file. The issue is I want to extract ONLY the formattedTime and value for my keywords.

JS not a strong suit of mine. How do I pull only these parameters? Or is there a way I can assign these parameters to key value dictionary pair?

Thank you.

json output

{
  "default": {
     "timelineData":[
       {
         "time":"1511629200",
         "formattedTime":"Nov 25, 2017 at 12:00 PM",
         "formattedAxisTime":"Nov 25 at 12:00 PM",
         "value":[44],
         "formattedValue":["44"]
       },
       {
         "time":"1511632800",
         "formattedTime":"Nov 25, 2017 at 1:00 PM",
         "formattedAxisTime":"Nov 25 at 1:00 PM",
         "value":[41],
         "formattedValue":["41"]
       }
     ]
   }
}

code

'use strict';

const googleTrends = require('google-trends-api');


var animals = ['hamsters', 'puppies'];


for (var key in animals) {

    console.log(animals[key]);

    googleTrends.interestOverTime({
        keyword: key,
        startTime: new Date(Date.now() - (167.9 * 60 * 60 * 1000)),
        granularTimeResolution: true,
    }, function(err, results) {

        if (err) 
            console.log('oh no error!', err);
        else 
            console.log(results);
        console.log("--------------------------")
    });
}
antihero989
  • 486
  • 1
  • 10
  • 32
BorangeOrange1337
  • 182
  • 1
  • 1
  • 20

2 Answers2

1

Extracting the required data into an object to follow a key/value pair pattern in a functional manner with existence checks:

function extractTimeAndValue(data) {
  var timelineData = (data && data.default && data.default.timelineData) || [];

  return timelineData.reduce(function(timeAndValueObject, timeline) {
    var time = timeline.formattedTime;
    var value = timeline.value;

    return Object.assign(
     {},
     timeAndValueObject,
     time && value ? {[time]: value} : {}
    );
  }, {});
}
antihero989
  • 486
  • 1
  • 10
  • 32
0

This could get you started with extracting what you want:

theStuffIWant = [];

for (each of output.default.timelineData) {
  theStuffIWant.push({time: each.formattedTime, value: each.value[0]});
}

console.log(theStuffIWant);

// now you should have an array of the data you want.

Note that the values look like they're in an array with one value, hence the need to use the [0] index. Also note that the variable output should be replaced with whatever variable holds your JSON data.

Glenn
  • 4,195
  • 9
  • 33
  • 41