Nested JSON Response coming back as [Object] using FB.API? - javascript

I know this is something really simple but for the life of me I can't figure out how to parse out the next level json request from this bit of javascript I'm writing in Node.js using the Facebook API.
Code:
for(var i = 0; i < userArrayLength; i++) {
fb
.api(usersArray[i] + '/posts?since=2017-05-17', { fields: ['from', 'id'], access_token: 'accessToken' }, function (res) {
console.log(res, {depth: null});
});
}
;
My return has the following:
from: [Object],
id: 'postid_xxxxxxxxxxxxxxxx',
I know that all I need to do is step down on level in the JSON to from:name but I just can't get the formatting correct and can't find any good examples online.
I'm new to node and javascript so I'm sure its just something boned headed. Would appreciate any help!
Thanks!

Related

Struggling to show data from javascript in html

Note: I am new to JavaScript and html so there are a lot of things i do not quite understand yet.
I am trying to make a web-application that uses a bus-schedule API to show the bus times around my apartment. I have managed to retrieve the data, but I struggle to display that data in the html. (edit: it is possibly a SDK, i dont really know the difference)
// this is the function write_bus() in my javascript file departures.js:
function write_bus() {
document.getElementById("bustime-kong").innerHTML = data;
}
// 'data' is a variable in javascript that contains the information I fetched from the client, and is what I am trying to show.It is on the following format:
const data = {
aimedArrivalTime: '2022-01-06T12:36:00+0100',
aimedDepartureTime: '2022-01-06T12:36:00+0100',
cancellation: false,
date: '2022-01-06',
destinationDisplay: {
frontText: 'xxx'
},
expectedDepartureTime: '2022-01-06T12:38:12+0100',
expectedArrivalTime: '2022-01-06T12:37:32+0100',
forAlighting: true,
forBoarding: true,
notices: [],
predictionInaccurate: false,
quay: {
id: 'xxx',
name: 'xxx',
publicCode: 'P2',
situations: [],
stopPlace: [Object]
}
}
<script src="departures.js"></script>
<input type="button" onclick="write_bus()" value="Busstider"> <br>
<div id="bustime-kong"></div>
(In order to save some space i removed 2/3 of the data)
I appreciate every bit of help i could get!
You can't insert raw objects like that as DOM text. You have to use specific properties, but if you are so inclined to insert object like that, use JSON.stringify() method.
document.getElementById("bustime-kong").innerHTML = JSON.stringify(data);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
BTW, It is good practice to put <script> tag at the end to make sure HTML is loaded before running any JavaScript.
You can create a function that will parse through the json and print it in table form like below.
// this is the function write_bus() in my javascript file departures.js:
function write_bus() {
document.getElementById("bustime-kong").innerHTML = createTable(data);
}
// 'data' is a variable in javascript that contains the information I fetched from the client, and is what I am trying to show.It is on the following format:
const data = {
aimedArrivalTime: '2022-01-06T12:36:00+0100',
aimedDepartureTime: '2022-01-06T12:36:00+0100',
cancellation: false,
date: '2022-01-06',
destinationDisplay: {
frontText: 'xxx'
},
expectedDepartureTime: '2022-01-06T12:38:12+0100',
expectedArrivalTime: '2022-01-06T12:37:32+0100',
forAlighting: true,
forBoarding: true,
notices: [],
predictionInaccurate: false,
quay: {
id: 'xxx',
name: 'xxx',
publicCode: 'P2',
situations: [],
stopPlace: [Object]
}
}
function createTable(data){
var table = "<table>";
for(var key in data){
table+="<tr>";
table+="<td>"+key+"</td>";
table+="<td>"+data[key]+"</td>";
table+="</tr>";
}
table+="</table>";
return table;
}
<input type="button" onclick="write_bus()" value="Busstider"> <br>
<div id="bustime-kong"></div>
Since it is array of data you need to use Json.stringify method,
document.getElementById("bustime-kong").innerHTML = JSON.stringify(data);

Semantic UI Search Module does not display json response

I am trying to get Semantic UI's Search autocomplete to work. Everything seems to be working, except for the fact that the autocomplete always says no results found.
This is an example search:
This is the case even though the server response seems to work fine.
Here is the server responding with JSON:
Finally, here is my JQuery code:
$(".ui.search").search({
apiSettings: {
url : "/subtopics/search.json?query={query}"
},
fields: {
results : 'subtopics',
title : 'name'
},
minCharacters : 2
})
;
From all the examples I've seen this is the proper way to tell Semantic UI what fields to look at, but it's not working.
Any help with this issue would be greatly appreciated.
It turns out using the onResponse callback included in the Semantic UI documentation (http://semantic-ui.com/behaviors/api.html#response-callbacks) is the solution to this problem.
Here is the code that ended up working:
$(".ui.search").search({
type: 'category',
minCharacters: 3,
apiSettings: {
onResponse: function(serverResponse) {
var
response = {
results: {}
}
;
//translate Server API response to work with search
$.each(serverResponse.subtopics, function(index, subtopic) {
var
topic = subtopic.topic || 'Unknown',
maxResults = 8
;
if(response.results[topic] === undefined) {
response.results[topic] = {
name: topic,
results: []
};
}
//add result to category
response.results[topic].results.push({
title: subtopic.name
});
});
return response;
},
url: "/subtopics/search.json?query={query}"
}
})
;

Sequelize: .createAssociation() or .setAssociation doesn't update the original object with created data

I've been stuck on this for a while. Take the following code as an example:
models.Summoner.findOne({
include: [{ model: models.RankedStats, as: 'SummonerRankedStats', required: true }],
where: { summonerId: summonerId, server: server }
}).then(function(summoner) {
models.RankedStats.create({
totalWins: 0,
totalLosses: 0
}).then(function(rankedStats) {
summoner.setSummonerRankedStats(rankedStats).then(function() {
console.log(summoner.SummonerRankedStats)
//This outputs undefined
summoner.getSummonerRankedStats().then(function(srs) {
console.log(srs)
//This outputs the RankedStats that were just created
})
models.Summoner.findOne({
include: [{ model: models.RankedStats, as: 'SummonerRankedStats', required: true }],
where: { summonerId: summonerId, server: server }
}).then(function(summoner) {
console.log(summoner.SummonerRankedStats)
//This outputs the SummonerRankedStats object
})
})
})
})
So, to put it simply... If I have a Summoner (var summoner) and perform a .setAssociation() or .createAssociation() on it, and then log summoner, the data created isn't there. If I fetch it again from the database (with .getAssociation() or by searching for that Summoner again) I can access it, but I was hoping to avoid that extra DB call.
Is there a way to add this information to the original object when using .create() or .set()? It can be achieved by doing something like:
summoner.dataValues.SummonerRankedStats = rankedStats
But that seems somewhat hacky :)
Is there a correct way to do it, or does it even make any sense?
Thanks in advance!

JS Object strange behaviour when trying access Loopback related model query

I am working with the Loopback Framework, doing a web project.
But I think that the question that I am exposing here has less to do with this, but with general Javascript / Node.JS knowledge.
At one part of the code, I am doing:
roleMapping.find({
where: {
principalType: 'USER',
principalId: context.principals[0].id
},
include: 'role'
}, function(err, roles){
console.log(roles[0]);
for (var i in roles)
{
if (roles[i].role.name === 'teamLeader' &&
roles[i].groupId === context.modelId)
{
cb(null,true);
}else {
cb(null,false);
}
}
});
Ok with this, but it fails when trying to compare roles[i].role.name.
So, I went logging what the roles[i] object contained.
{ groupId: 1,
id: 3,
principalType: 'USER',
principalId: 1,
roleId: 2,
role:
{ id: 2,
name: 'teamLeader',
description: 'The leader(s) of a team',
created: null,
modified: null } }
Ok, nothing wrong, but it still fails, so I tried to print just the role property. And to my surprise:
{ [Function]
update: [Function],
destroy: [Function],
create: [Function],
build: [Function],
_targetClass: 'Role' }
So, the role property seems to be some sort of function? But how it was been correctly printed before?
Eventually, lost in my frustration I tried var role = JSON.parse(JSON.stringify(roles[i]));
And then I could access every property of the object normally, but this is not clean nor normal.
This blew my mind for the first time in years of JS programming (sort of amateurish though), and I would be pleased if someone could clarify this to me. Thanks
EDIT: It seems that it is specific to this Framework, so I'm changing title to help community.
I just found issue 1425 which links to the following docs:
With Node.js API, you need to call toJSON() to convert the returned model instance with related items into a plain JSON object
Please note the relation properties […] points to a JavaScript function for the relation method.
So it seems you have to use
for (var i=0; i<roles.length; i++) {
var x = roles[i].toJSON();
cb(null, x.role.name === 'teamLeader'
&& x.groupId === context.modelId);
}

Nested attributes with Angular.js

I have been racking my brain and google all morning trying to figure this out but I have come to the conclusion that I need to ask the experts! I am trying to do nested attributes with Sinatra and Angular, don't worry about the Sinatra side of things I am just trying to get the data to the server side in the correct manner at the moment. Please see the code below for an explanation of
My Input:
<input type="text" placeholder="{{item.placeholder}}" ng-model="question.possible_answer_attributes[$index][title]" class="form-control" />
My model object:
$scope.question = new Question({
poll_id: parseInt($routeParams.id),
title: '',
kind: 'open',
possible_answer_attributes: [] // I believe the issue may lie here
});
My factory:
.factory('Question', function($resource) {
return $resource('/api/questions/:id', { id: '#id' }, {
'update' : { method: 'PUT' },
'get_by_poll' : { method: 'GET', url: '/api/questions_by_poll/:id', isArray: true }
});
})
My object at time of running save function:
{"poll_id"=>1, "title"=>"123123", "kind"=>"multiple", "possible_answer_attributes"=>[{"undefined"=>"412312"}, {"undefined"=>"1234124"}, {"undefined"=>"234235234"}]}
I do not understand why my "possible_answer_attributes" keys are coming through as "undefined". It may be something very simple that I have missed, but any feedback would be great!
Thanks in advance!
In order to address the title property, you would need to use a string to index into the object:
ng-model="question.possible_answer_attributes[$index]['title']"
This should hold as long as possible_answer_attributes array looks like:
[{ title: 'my title' }]

Categories

Resources