简体   繁体   中英

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.

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.

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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