How to retrieve an [object Object] value in a Twitter API response - javascript

I'm currently using a twitter API (twit npm package) and I am currently getting a response with the structure like so
{ metadata: [Object],
I20150213-22:24:29.155(0)? created_at: 'Fri Feb 13 22:24:07 +0000 2015',
I20150213-22:24:29.156(0)? id: 566362206468845600,
I20150213-22:24:29.156(0)? id_str: '566362206468845569',
I20150213-22:24:29.157(0)? text: 'Photo: New BTS picture from Mockingjay part http://t.co/fo30mcLRYV',
I20150213-22:24:29.158(0)? source: 'Tumblr',
I20150213-22:24:29.158(0)? truncated: false,
I20150213-22:24:29.159(0)? in_reply_to_status_id: null,
I20150213-22:24:29.159(0)? in_reply_to_status_id_str: null,
I20150213-22:24:29.160(0)? in_reply_to_user_id: null,
I20150213-22:24:29.160(0)? in_reply_to_user_id_str: null,
I20150213-22:24:29.161(0)? in_reply_to_screen_name: null,
I20150213-22:24:29.161(0)? user: [Object],
I20150213-22:24:29.162(0)? geo: null,
I20150213-22:24:29.162(0)? coordinates: null,
I20150213-22:24:29.163(0)? place: null,
I20150213-22:24:29.163(0)? contributors: null,
I20150213-22:24:29.164(0)? retweet_count: 0,
I20150213-22:24:29.288(0)? favorite_count: 0,
I20150213-22:24:29.289(0)? entities: [Object],
I20150213-22:24:29.289(0)? favorited: false,
I20150213-22:24:29.290(0)? retweeted: false,
I20150213-22:24:29.290(0)? possibly_sensitive: false,
I20150213-22:24:29.291(0)? lang: 'en' },
I am trying to retrieve the entities object to access the potential media items inside it however when I console.log() the entities key in this Array [object Object] gets logged. How do I access the inside of the object? I intend to extract a picture url from inside this object but I can't see whats inside. According to the Twitter API website media is stored inside entities objects.
Any help would be appreciated.

The URL's to the image is stored inside the entity media in the JSON response the REST call returns.
Say you want to access the media_url entity, simply access it as below
var result = the result from your call...
var imageUrl = result.entities.media.media_url;
and use the media URL in whatever way you want.
If you want to check the existence of media content, simply use if(result.entities.media.length > 0).

Related

Need explanation on structure of Object in Node.js

I did a console.log of some parameter that is available to a callback function in the Node.js formidable package. I am using this package for processing file uploads. The output of the console.log(files) is:
{
fileUpload: [
PersistentFile {
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
lastModifiedDate: 2023-02-16T19:45:33.257Z,
filepath: '/home/uploads/someName',
newFilename: '8655b57ce96e3b679ffdd7e00',
originalFilename: 'anotherFile.jpg',
mimetype: 'image/jpeg',
hashAlgorithm: false,
size: 7,
_writeStream: [WriteStream],
hash: null,
[Symbol(kCapture)]: false
}
]
}
I am expecting an object with each key('fileUpload', for example) having as value an array of objects. I am unable to understand the role of PersistentFile in the object's structure. I think that it breaks the conventional structure of an object. It gives a syntax error if I try to copy/paste it to a variable.
How can I process this data structure (or object, or whatever...) in Javascript?
EDIT:
My need is to get only properties from this object which have scalar values only: lastModifiedDate, filepath, originalFilename, mimetype, and size. So the resultant object will be:
{
fileUpload: [
{
originalFilename:
filepath:...
...
},
{
originalFilename:
filepath:...
...
}
],
fileField2: [
{...},
{...}
...
],
...
}
This object contains a WriteStream object which is not serializable in JSON because it has a live file handle in it. You could copy select properties out of this into a new object and then serialize that using JSON.stringify().

getting information from a javascript json object

I imagine this has been posted before but I wasn't able to find a data object specifically like this one. I'm struggling to understand how extract information from this data object in javascript. It's a parsed URL.
data = URL {
href: 'http://localhost:8080/test.txt?cat=Mouse',
origin: 'http://localhost:8080',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:8080',
hostname: 'localhost',
port: '8080',
pathname: '/test.txt',
search: '?cat=Mouse',
searchParams: URLSearchParams { 'cat' => 'Mouse' },
hash: ''
}
I can retrieve the URLsearchParams
data.searchParams, which returns { 'cat' => 'Mouse' }
What is this data structure called: { 'cat' => 'Mouse' }. I'm confused by the =>
And how do I retrieve the two objects 'cat' and 'Mouse' separately inside this data structure?
For example, retrieving then setting a variable equal to the first item, 'cat' and another variable equal to 'Mouse'
Thank you
What is this data structure called: { 'cat' => 'Mouse' }.
That isn't a data structure. It's a visual representation of the data in the URLSearchParams object.
Look at the API documentation to see how to access it (e.g. data.searchParams.entries())
There is absolutely nothing JSON related to that.

Find Attendees of an Event

I am trying to display events from a "public" google calendar. My requirement is to get the number of attendees (not necessarily the names of the attendees). However, when I get the events using the Calendar API (using an API Key and CalendarID); the event is missing the whole attendees section that is mentioned here.
My question: Do I need to be authenticated ? Does this mean this can't be public, and the web-pages that displays this information will need the "viewer" to authenticate to Google first?
Here is a snippet of my code (edited)...
$.ajax({
type: 'GET',
url: encodeURI('https://www.googleapis.com/calendar/v3/calendars/' + calendarId+ '/events?key=' + myKey),
dataType: 'json',
success: function (response) {
console.log(response);
//here is where I need to get the number of participants
},
error: function (error) {
console.log(error);
//tell that an error has occurred
}
Here is the output...
{kind: 'calendar#events', etag: '"p324e9j5nqabva0g"', summary: 'EDWC Schedule', description: '', updated: '2022-01-04T08:09:10.933Z', …}
accessRole: 'reader'
defaultReminders: (0) []
description: ''
etag: '""'
items: (2) [{…}, {…}]
0: {kind: 'calendar#event', etag: '""', id: '', status: 'confirmed', htmlLink:…}
1: {kind: 'calendar#event', etag: '""', id: '', status: 'confirmed', htmlLink:…}
conferenceData: {}
created: ''
creator: {}
description: ''
end: {dateTime: '2022-01-08T16:00:00+11:00', timeZone: 'Australia/Sydney'}
etag: ''
eventType: 'default'
hangoutLink: ''
htmlLink: ''
iCalUID: ''
id: ''
kind: 'calendar#event'
location: 'Australia'
organizer: {email: '', displayName: '', self: true}
sequence: 0
start: {dateTime: '2022-01-08T13:00:00+11:00', timeZone: 'Australia/Sydney'}
status: 'confirmed'
summary: ''
updated: '2022-01-04T08:09:10.933Z'
[[Prototype]]: Object
[[Prototype]]: Object
length: 2
[[Prototype]]: Array(0)
kind: 'calendar#events'
nextSyncToken: 'CIjkzLfSl_UCEAAYASCvg6XIAQ=='
summary: ''
timeZone: 'Australia/Melbourne'
updated: '2022-01-04T08:09:10.933Z'
[[Prototype]]: Object
You can accomplish this using the Google Api Node.js Client in this manner:
Google Calendar Event Attendees                                                                                
Run in Fusebit
const calendarClient = googleClient.calendar('v3');
// Update the below fields with your desired values
const calendarId = 'YOUR_CALENDAR_ID';
const eventId = 'YOUR EVENT_ID';
const response = await calendarClient.events.get({
calendarId,
eventId,
});
const attendees = response.data.attendees;
As per your question, the answer is yes. Every request sent to the Google Calendar API must include an authorization token. Now, that authorization does not always entail a consent screen, it can also be a short-lived access token or an API key (like in your example). I would encourage you to read more about the authorization process here.
As per your code snippet and response, the events list is located inside the items property of the response object. Here you can find how the response object is structured, but in a nutshell, you can access the events by looping through the items like this:
for (var event of response['items']){}

Printing Object doesnt contain all keys

Im completely lost. This is some test code I use to print a specific key of an object, then im printing the entire object.
console.log(docs[0].mc_ign);
console.log(docs[0]);
Now this is the output I see on the console:
The__TxT
{
id: 0,
status: 1,
testing: false,
_id: 5dbc17eb20b3a8594d569570,
timestamp: 2019-11-01T11:32:59.380Z,
mc_uuid: 'dac89e44d1024f3b810478ed62d209a1',
discord_id: '653029505457586176',
email_address: 'gut97930#eveav.com',
country: 'Germany',
birth_month: 3,
birth_year: 1943,
about_me: 'about me text',
motivation: 'motivation text',
build_images: '',
publish_about_me: true,
publish_age: false,
publish_country: true,
__v: 0
}
Where is the mc_ign key?
The object itself comes from mongoose, the missing key is added by me after the fact:
docs[i].mc_ign = mc_ign;
I tried logging the entire object before and after I add the key and assign the value. They are both the same.
What am I missing? Why can I read the value out, but cant see it?
It is mongoose document object. To achieve what you want do the following.
docs[0] = docs[0].toObject();
docs[0].mc_ign = "stuff";
console.log(docs[0])
.toObject() convert it to plain JS object.

NodeJS/AngularJS - Reading Array of Objects from JSON

I've got an issue reading a nested array from JSON(BSON from MongoHQ) using Node and Angular.
JSON snippet: http://pastie.org/9305682. Specifically look for the edges array.
Mongoose model: http://pastie.org/9305685
Basically I call the character from the DB and then attempt to log it to the console with
console.log(char); before sending it back to the angular call with res.json(char); 'char' is the returned character from the databased saved as my mongoose model.
Attempting to log the character to the console. I get everything looking normal except for the portions with the nested "effects" arrays. Anywhere they show up I receive the following:
edges:
[ { name: 'Super Hacker', notes: '', effects: [Object] },
{ name: 'Witty', notes: '', effects: [Object] },
{ name: 'Attractive', notes: '', effects: [Object] },
{ name: 'Encyclopedic Memory',
notes: 'Prereq: d8 Smarts',
effects: [Object] },
{ name: 'Daywalker', notes: '', effects: [Object] },
{ name: 'Tough', notes: '', effects: [Object] } ],
From here if I try to call it with:
From NodeJS - console.log(char[0].edges[0].effects[0].type); - Returns undefined.
From Angular View - {{cur_char.edges[0].effects[0].type}} - Displays nothing.
Thanks in advance for the help. Let me know if I can provide more in.
I think what you're asking is how to see more depth to the object in the console output. You can use util.inspect to print out more information:
console.log(util.inspect(char, { depth: 5 }));
By default util.inspect only goes to a depth of 2 which explains why you can only see the contents of the array (1) and the primitive properties of each element in the array (2).
See: http://nodejs.org/api/util.html#util_util_inspect_object_options

Categories