console.log(result.data[0]);
returns:
{ name: 'page_stories',
period: 'day',
values:
[ { value: 114, end_time: '2016-07-31T07:00:00+0000' },
{ value: 68, end_time: '2016-08-01T07:00:00+0000' },
{ value: 134, end_time: '2016-08-02T07:00:00+0000' } ],
title: 'Daily Page Stories',
description: 'Daily: The number of stories created about your Page. (Total Count)',
id: '462582393917692/insights/page_stories/day' }
but for some reason var name = result.data[0].name; is returning:
TypeError: Cannot read property 'name' of undefined
I can't for the life of me figure out why. the 'name' property clearly exists as does the result.data[0] object. Any help would be fantastic.
edit: found out that the data format wasn't uniform for every single request (just most!). Thanks for the responses. I should've made it clear that I was feeding batch requests through this code too.
Ensure that you are actually trying to access an object and not a string. JSON.parse(obj) if needed.
Related
I have data in the format (input):
doSomething({
type: 'type',
Unit: 'unit',
attributes: [
{
attribute: 'attribute',
value: form.first_name
},
{
attribute: 'attribute2',
value: form.family_name
}
],
groups: [
{
smth: 'string1',
smth2: 'string2',
start: timeStart.substring(0, 9)
}
]
})
I managed to take out the doSomething part with the parenthesis as to load the function from the corresponding module with
expression.split('({',1)[0]
However using the loaded function with the rest, obtained with:
expression.split(temp+'(')[1].trim().replace(/\n+/g, '').slice(0, -1)
does not work because it should be an object and not a string. Hardcoding the data in does work as it is automatically read as an object.
My question is if there is any way of converting the string that I get from the user and convert it to an object. I have tried to convert it to a json object with JSON.parse but I get an unexpected character t at position 3. Also I have tried new Object(myString) but that did not work either.
What I would like is to have the body of the provided function as an object as if I would hard code it, so that the function can evaluate the different fields properly.
Is there any way to easily achieve that?
EDIT: the "output" would be:
{
type: 'type',
Unit: 'unit',
attributes: [
{
attribute: 'attribute',
value: form.first_name
},
{
attribute: 'attribute2',
value: form.family_name
}
],
groups: [
{
smth: 'string1',
smth2: 'string2',
start: timeStart.substring(0, 9)
}
]
}
as an object. This is the critical part because I have this already but as a string. However the function that uses this, is expecting an object. Like previously mentioned, hard coding this would work, as it is read as an object, but I am getting the input mentioned above as a string from the user.
Aside: I know eval is evil. The user could do by this certain injections. This is only one possibility to do this there are certain other ways.
I just added before "output =", cut from the input-string the "doSomething(" and the last ")". By this I have a normal command-line which I could execute by eval.
I highly not recommend to use eval this way; especially you don't
know what the user will do, so you don't know what could all happen
with your code and data.
let form = {first_name: 'Mickey', family_name: 'Mouse'};
let timeStart = (new Date()).toString();
let input = `doSomething({
type: 'type',
Unit: 'unit',
attributes: [
{
attribute: 'attribute',
value: form.first_name
},
{
attribute: 'attribute2',
value: form.family_name
}
],
groups: [
{
smth: 'string1',
smth2: 'string2',
start: timeStart.substring(0, 9)
}
]
})`;
let pos= "doSomething(".length;
input = 'output = ' + input.substr(pos, input.length-pos-1);
eval(input);
console.log(output);
Currently, I'm trying to retrieve a particular property from a javascript object returned by mongoose.
I can see the property when printing the whole object, but when trying to use it, I get an undefined. Here's the code:
Match.findOne({id: match.id}, function (err, match) {
console.log(match)
console.log(typeof match)
console.log(match.id)
console.log(match.winner)
})
The output of that is:
{ _id: 552c7f2925efcbc88ccc55bf,
id: 499142595,
region: 'br',
winner: 200,
championsLose: [ 25, 96, 81, 113, 63 ],
championsWin: [ 37, 238, 201, 268, 81 ]
}
object
499142595
undefined
Even though the 'winner' property is clearly there.
Any ideas?
UPDATE: added more logging to the above code and results of it
It's odd that there are no quotes around the value of associated with the key "_id":
{ _id: 552c7f2925efcbc88ccc55bf, // should be --> "552c7f2925efcbc88ccc55bf"
id: 499142595,
region: 'br',
winner: 200,
championsLose: [ 25, 96, 81, 113, 63 ],
championsWin: [ 37, 238, 201, 268, 81 ]
}
This seems to indicate that it is not actually an object. Which, of course, explains why match.winner is undefined. I would do console.log(typeof match) and see what it says.
console updates("Live Update") the last references if the object/property is change even after console.log(). i have recently got this pain using chrome
it might be the case
check this example in chrome, dont know how this problem behaves in node console or the tool you are using
obj = {a:"b",b:"c"};
console.log(obj); // logs Object { b: "c" } not {a:"b",b:"c"}
delete obj.a;
console.log(obj);// logs Object { b: "c" }
you might have deleted the match.winner property later in the code. that seems to be the case only
Finally the issue wasn't in that piece of code, but in the Model definition. The variable name wasn't updated properly, so the old name was still being used there:
var mongoose = require('mongoose');
module.exports = mongoose.model('Match',{
id: Number,
region: String,
championsWin: Array,
championsLose: Array,
winnerTeamId: Number
});
And the proper model should be:
module.exports = mongoose.model('Match',{
id: Number,
region: String,
championsWin: Array,
championsLose: Array,
winner: Number
});
Thanks a lot for the help!
I have a problem here, and I can't find out how to solve it. I have an object with many levels. There is arrays with objects inside my object, and they have their arrays with objects too. Let me show you somekind of example here:
{
sections: [
{
currency_sections: [
{
positions: [
{
id: 131,
quantity: 24
},
{
id: 133,
quantity: 1
}
],
key: value,
key: value
},
{
positions: [
{
id: 136,
quantity: 2
},
{
id: 137,
quantity: 3
}
],
key: value,
key: value
}
],
key: value,
key: value
}
],
key: value,
key: value
}
I build my data via handlebars template. Which is not really important. But on my page I can change, let's say, quantity of the position. When I do that I have only id of the position I changed and new quantity.
So basically I need to filter my object to find one object in positions arrays that matches via id key and change quantity there.
Also I can delete whole position, and in that case I need to find position object with id needed and delete whole object.
The thing I can't understand is how I can filter all my data at once. And how can I manipulate unnamed object if I will find it.
And let's say I filtered it somehow. Can I return full path to that object for later use? In example - sections[0].currency_sections[1].positions[0] ? Because if I can do that than deleting and editing should be simple enough.
At this point I don't really have the time to redo everything on something more suitable like angular or ember. Although I have underscore and jquery.
Just wanted to update my question. At the end I just created a method that builds index of my elements.
function _createItemsIndex(data) {
if (!$.isEmptyObject(data)) {
$.each(data.sections, function (sectionIndex, section) {
$.each(section.currency_sections, function (curSecIndex, curSec) {
$.each(curSec.positions, function (positionIndex, position) {
_items.push({
id: position.id,
quantity: position.quantity,
price: parseFloat(position.price) || 0,
index: [sectionIndex, curSecIndex, positionIndex]
});
});
});
});
}
}
Thank you levi for your comments
I have the following code in javascript in my node.js application.
However certain objects are not stored in my variable appointment. Even if I set them, when I directly access them it works: console.log(appointment.test);
What have I done wrong in this code?
var appointment = {
subscribed: false,
enoughAssis: false,
studentSlotsOpen: false
};
console.log(appointment);
for (var key in appointmentsDB[i]) {
appointment[key] = appointmentsDB[i][key];
}
appointment.test= "res";
console.log(appointment.test);
console.log(appointment);
And here is the produced output:
{ subscribed: false,
enoughAssis: false,
studentSlotsOpen: false }
res
{ comment: 'fsadsf',
room: 'dqfa',
reqAssi: 3,
maxStud: 20,
timeSlot: 8,
week: 31,
year: 2013,
day: 3,
_id: 51f957e1200cb0803f000001,
students: [],
assis: [] }
The variable console.log(appointmentsDB[i]) looks as:
{ comment: 'fsadsf',
room: 'dqfa',
reqAssi: 3,
maxStud: 20,
timeSlot: 8,
week: 31,
year: 2013,
day: 3,
_id: 51f957e1200cb0803f000001,
students: [],
assis: [] }
The following command:
console.log(Object.getOwnPropertyNames(appointmentsDB[i]), Object.getOwnPropertyNames(Object.getPrototypeOf(appointmentsDB[i])));
Shows:
[ '_activePaths',
'_events',
'errors',
'_maxListeners',
'_selected',
'_saveError',
'_posts',
'save',
'_pres',
'_validationError',
'_strictMode',
'isNew',
'_doc',
'_shardval' ] [ 'assis',
'timeSlot',
'db',
'_schema',
'id',
'base',
'day',
'collection',
'reqAssi',
'constructor',
'comment',
'year',
'room',
'students',
'week',
'_id',
'maxStud' ]
However I would expect that my last output also provides the entries test, subscribed, enoughAssis and studentSlotsOpen. What is wrong in this code?
The solution I found was to manually copy the elements I wanted to.
You probably have a Document object instead of a plain object. Those have a custom toJSON method which only yields the properties of your schema and the _id, but nothing else. If you are copying that method with your for-in-loop onto the appointment object, it will get serialized differently as well when logged.
Try
for (var key in appointmentsDB[i].toObject()) {
appointment[key] = appointmentsDB[i][key];
}
appointment.test= "res";
console.log(appointment);
So I have something along the lines of:
events: [
{
id: 1,
name: 'Birthday Party',
organiser: {
id: 1,
name: 'Jill'
},
attendees: [
{
id: 2,
name: 'Bob'
},
{
id: 3,
name: 'Jill'
}
]
}
]
As usual: Events have a name, it has attendees but I'm also looking at having one organiser.
So I've setup my HasOne proxy within the Event to HasOne Organiser and I'm trying to create the Organiser object and attach it to the Event within the console but am having no luck.
I tried something like this, as the documentation says there should be a setter created... although only seems to give example for setting an ID (which also doesn't work).
var event = Ext.create('App.model.Event', {id: 1, name: 'Birthday Party'});
event.getOrganiser(); // says undefined
event.setOrganiser({
id: 1,
name: 'Jill'
}); // says TypeError: Object #<Object> has no method 'get'
event.setOrganiser(1); // As the example but it still says the TypeError message
event.setOrganiser(Ext.create('App.model.Organiser', {
id: 1,
name: 'Jill'
}); // says TypeError: Object #<Object> has no method 'get'
So I'm confused... examples from Doc don't seem to be working for me but I need to pass in the rest of the data anyway. No idea how to approach this without spending an entire day going into the source code, dumping and breakpointing everything.
Any ideas? Should I be able to do any of the above or is it not meant to work that way? I want to POST both the Event and the Organiser object with one call... so was expecting JSON like this when I do event.save();
{
id: 1,
name: 'Birthday Party',
organiser: {
id: 1,
name: 'Jill'
}
}
Sorry if you've seen this on the ST forum but it seems to be a ghost town
Thanks for any pointers or help :)
Updated to ST 2.0.1.1 and this is what worked:
event.setOrganiser(Ext.create('App.model.Organiser', {
id: 1,
name: 'Jill'
});