【问题标题】:How to Grab Value in Key/Value Pair in JavaScript - Google Trends API如何在 JavaScript 中获取键/值对中的值 - Google Trends API
【发布时间】:2017-12-04 03:22:43
【问题描述】:

我正在使用google trends API 最终将趋势数据导出到 Excel 文件。问题是我只想提取我的关键字的格式化时间和值。

JS 不是我的强项。我如何只提取这些参数?或者有没有办法可以将这些参数分配给键值字典对?

谢谢。

json 输出

{
  "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"]
       }
     ]
   }
}

代码

'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("--------------------------")
    });
}

【问题讨论】:

  • 你的 JSON 对象也有一个错误的额外 }

标签: javascript node.js api key-value google-trends


【解决方案1】:

将所需数据提取到对象中,以通过存在检查以功能方式遵循键/值对模式:

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} : {}
    );
  }, {});
}

【讨论】:

    【解决方案2】:

    这可以让你开始提取你想要的东西:

    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.
    

    请注意,这些值看起来像是在一个只有一个值的数组中,因此需要使用[0] 索引。另请注意,变量 output 应替换为包含您的 JSON 数据的任何变量。

    【讨论】:

    • 得到“类型错误:无法读取未定义的属性‘默认’。
    猜你喜欢
    • 2018-09-12
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 2012-04-12
    相关资源
    最近更新 更多