简体   繁体   English

如何在javascript中访问此对象中的元素?

[英]how to access elements from this object in javascript?

i was trying to get number of hashtags used at specific time using twitter api and an npm module hashtag-count.this is the program and the results is generating the object below.我试图使用 twitter api 和 npm 模块 hashtag-count 获取特定时间使用的主题标签数量。这是程序,结果生成下面的对象。

var HashtagCount = require("hashtag-count")
require('dotenv').config();

var hc = new HashtagCount({
  'consumer_key': process.env.CONSUMER_KEY,
  'consumer_secret': process.env.CONSUMER_SECRET,
  'access_token': process.env.ACCESS_TOKEN,
  'access_token_secret': process.env.ACCESS_TOKEN_SECRET
});

// //giving the hashtags for which we want to see the count
 var hashtags = ['a', 'b', 'c'];
// //time interval
 var interval = '10 seconds';
//time limit for the program
var limit = '30 seconds';
var finishedCb = function (err, results) {
  if (err) {
    console.error(err);
  } else {
      console.log(results);
  }
};
//initializing.
hc.start({
  hashtags: hashtags,       
  interval: interval,       
  limit: limit,             
  finishedCb: finishedCb,   
});

{
  '2020-01-10T22:46:36.042Z': { a: 1, b: 9, c: 16 },
  '2020-01-10T22:46:46.048Z': { a: 0, b: 10,c: 12 },
  '2020-01-10T22:46:56.063Z': { a: 2, b: 8, c: 15 }
}

this is the object that i have and i would like to get the values of a , b and c from this object.这是我拥有的对象,我想从这个对象中获取 a 、 b 和 c 的值。

You have a lot of methods to do that.你有很多方法可以做到这一点。 First of all, you can just get all keys of your object, and just navigate with it.首先,您可以获取对象的所有键,然后使用它进行导航。

I've take your example and add it into a javascript variable like this:我以你的例子为例,将它添加到一个 javascript 变量中,如下所示:

let object = {
  '2020-01-10T22:46:36.042Z': { a: 1, b: 9, c: 16 },
  '2020-01-10T22:46:46.048Z': { a: 0, b: 10,c: 12 },
  '2020-01-10T22:46:56.063Z': { a: 2, b: 8, c: 15 }
};

If you need to get a, b, c from your object with the date, you can do this:如果您需要从带有日期的对象中获取a, b, c ,您可以这样做:

console.log(object['2020-01-10T22:46:36.042Z']);

Or, if you just need to add up these values, you can do this (more readable and clean):或者,如果您只需要将这些值相加,您可以这样做(更易读和干净):

let results = {'a': 0, 'b': 0, 'c': 0};

Object.keys(object).forEach(function(key) {
    results['a'] += object[key]['a'];
    results['b'] += object[key]['b'];
    results['c'] += object[key]['c'];
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM