Console.log of function returning object - javascript

So I have a function which is returning an object which has an object as value. I need to console.log the result of the function, however what I get is this:
testedDatalayer: {
event: 'mkt_pageInformation',
eventDetails: { page: [Object], pagePath: '/' }
}
I need to display the value as normal instead of [Object]. I know I can stringify it, however I really want to keep it as an object rather then string and make it look like this:
expectedDataLayer: {
event: 'mkt_pageInformation',
page: { type: 'xxx', category: 'xxxx' },
pagePath: 'xxxxx'
},
Is there any way of keeping that structure and console logging the function without the need of strinfigy?
EDIT: doing it on node.js and logging to cmd

You can try console.dir() instead of console.log()

If you're using Node, you could try using util.inspect:
const inspect = require('util').inspect;
console.log(inspect(yourObject,{depth: Infinity}));
For more info you could check the nodejs docs for it at:
https://nodejs.org/api/util.html#util_util_inspect_object_options

You can format it as an object structure using JSON.stringify() third parameter to pretty print Object.
var objectToLog = {
expectedDataLayer: {
event: 'mkt_pageInformation',
details: { page: { type: 'xxx', category: 'xxxx' } },
pagePath: 'xxxxx'
}
}
console.log(JSON.stringify(objectToLog,null,4));

Related

make the query dynamically to change using sanity.io groq

Hi there I'm trying to make a post request where I want to update one field on sanity.io
this is my query
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
`rewardItem[_key == \"${key}\"].lastTimeReward`: "TEst",
},
}
but this won't let me even run my project,
its giving me this error on console.log: Unexpected token;
When I do my query like this, it works
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
"rewardItem[_key == \"e88959e43ce7\"].lastTimeReward": "Test",
},
}
}]
Thanks a lot.
Your set-property is an object, and you can't enter a dynamic key directly into the object. To do what you are trying to do here, you can wrap the dynamic key in square brackets like this. That should give you the output you desire
const variable = "example"
const a = { [`template ${variable}`]: "value" }
console.log(a)

passing in json variable into sendgrid's dynamic_template_data

I'm having some trouble passing into a variable that holds a json object into sendgrid's dynamic_template_data. My setup looks like this:
const send = async (address, mentions) => {
console.log('mentions json obj', mentions)
let name = "john"
try {
let config = {
headers: {
Authorization: `Bearer ${process.env.sendgridKey}`,
}
}
let data = {
personalizations: [
{
to: [
{
email: `${address}`,
},
],
dynamic_template_data: {
name: name,
allMentions: mentions
}
}
],
from: {
email: "email#email.com",
name: "Mentionscrawler Team"
},
template_id: process.env.template_id,
}
await axios.post("https://api.sendgrid.com/v3/mail/send", data, config)
} catch (error) {
console.error(error, 'failing here>>>>>>>')
}
}
when I console.log mentions, which is json, and paste the code I get from the terminal directly into the allMentions key, it works. but when I just pass in mentions itself, nothing shows up on the sent email. I've been very confused the last few hours why this is happening. Any advice appreciated.
edit: i should also note that allmentions is an object with keys that hold arrays. So I'm looking to iterate over those arrays. Again, this totally all works if I just paste in directly what mentions is, but passing in mentions is giving me an issue.
Thank you very much,
just realized what was wrong. sendgrid's template requires a json object, so I assumed that I needed to use json.stringify on my mentions obj. Turns out I didn't need to do that, as long as all values are in string format.

Extracting values from multiple scope inside an array

I'm building a twitter bot that takes input of someone that DM's my account, and then will output the received DM's into tweet. I'm using twit package from npm. The question is, how do you extract the id's from the output, and then use the id's in another function in order to post the tweet, using? (note that I'm currently using console.log as the tweet for now).
Input command to check the direct messages
var listMsg = T.get('direct_messages/events/list', {
count: '50'
}, function(data, response) {
console.log(response)
Output in terminal (the multiple scope inside the events array)
{
events: [
{
type: 'message_create',
id: '1275746339314216965', //take this
created_timestamp: '1592996604170',
message_create: [Object]
},
{
type: 'message_create',
id: '1274664227584671750', //and this
created_timestamp: '1592738608629',
message_create: [Object]
}
]
}
Getting the content of a direct message
var getMsg = T.get('direct_messages/events/show', {
id:'1274664227584671750' //put it to this
}, function(data, response) {
//console.log(response)
let dm = response.event.message_create.message_data
console.log(dm) //and print the message here
The content of the direct message
{
text: 'Abcd',
entities: { hashtags: [], symbols: [], user_mentions: [], urls: [] }
}
I want to get the id's as a let just like in the third code block.
You can simply use the map array function to transform the object like this
events.map( function(e) { return e.id}) or you can use es6 syntax events.map(e=> e.id)
both would return an array like this
["1275746339314216965", "1274664227584671750"]
These could be joined into into a string like so
events.map(e=> e.id).join(",")
returning
"1275746339314216965,1274664227584671750"
map() is a great function try playing around with map reduce and filter to really improve your programming. There's a great article on them here https://medium.com/poka-techblog/simplify-your-javascript-use-map-reduce-and-filter-bd02c593cc2d
Of course you could do also use a good old fashioned for loop, but think that would be a bit verbose and unnecessary (the software equivalent of making your own hammer)
e.g.
var ids = []
for(var event of events) {
ids.push(event.id)
}

Trying to dynamically populate an object where one or more fields being passed are null

I have a node/express/mongoose project where I'm not getting something...
I have an endpoint where I'm passing in an object, to populate another object.
The first object may not have all the values needed to populate the new object.
I've tried a number of ways to check each field and if there isn't a matching field in the req.body, then just add a '' to it.
So here is the object I'm trying to build:
var share = {
facebook: {
item: req.body.facebook.item,
_id: req.body.facebook._id
},
linkedin : {
item: req.body.linkedin.item,
_id: req.body.linkedin._id
},
google: {
item: req.body.google.item,
_id: req.body.google._id
}
};
and let's say the object I'm passing in looks like this:
var share = {
facebook: {
item: req.body.facebook.item,
_id: req.body.facebook._id
},
google: {
_id: "5c18929c75727bad4144c0a8"
}
};
As you can see, 'linkedin' is missing all together, and 'google' is missing the 'item' field.
How do I check to see if a field is missing, then populate it with '_blank' fields so I keep the structure of the object the way I need it to be?
Otherwise, I end up with the dreaded: error: "Cannot read property 'item' of undefined" returned.
Thanks!
Try to map the object and check if this property is set if it is not then fill it with blank.

How to make a JSON object?

I want to create the following JSON object, as seen from a console log:
Object
. member: Object
. id: 8286
I've been trying:
'member' :[{'id': 8286}]
but get the following error: "Uncaught SyntaxError: Unexpected token :"
What am I doing wrong? Thanks
var member = {
id: 8286
};
this allows you to access it like
member.id
You could have also meant something like:
var data = {
member: {
id: 8286
}
};
which you would access like so:
data.member.id
If this is not what you want, please clarify in your post cause I'm not sure I'm following your request correctly.
You're missing the curly braces surrounding the object.
As in:
var x = {'member': [{'id':8286}]};
You mean something like this?
{
"member": {},
"id": 8286
}
{
"member":{
"id":value
},
{
another_data:value
}
}
the data are accesses using the(.) operator.
the id is accessed by member.id

Categories

Resources