Hy,I have a data, I will create hierarchical data example
{
id_commentForum: 1,
id_user: 1,
id_thread: 1,
comment: 'Ini Komentar Pertama',
parent: 0,
created_at: Wed Jun 22 2016 13:36:38 GMT+0700 (WIB),
updated_at: Wed Jun 22 2016 13:36:38 GMT+0700 (WIB),
name: 'fahmy Abdul Aziz',
avatar: '/images/img/avatar/100x100/201661154914.jpg',
child : [{
id_commentForum: 1,
id_user: 1,
id_thread: 1,
comment: 'Ini Komentar Pertama',
parent: 0,
created_at: Wed Jun 22 2016 13:36:38 GMT+0700 (WIB),
updated_at: Wed Jun 22 2016 13:36:38 GMT+0700 (WIB),
name: 'fahmy Abdul Aziz',
avatar: '/images/img/avatar/100x100/201661154914.jpg',
child : [{
id_commentForum: 1,
id_user: 1,
id_thread: 1,
comment: 'Ini Komentar Pertama',
parent: 0,
created_at: Wed Jun 22 2016 13:36:38 GMT+0700 (WIB),
updated_at: Wed Jun 22 2016 13:36:38 GMT+0700 (WIB),
name: 'fahmy Abdul Aziz',
avatar: '/images/img/avatar/100x100/201661154914.jpg',
}]
}
{
id_commentForum: 1,
id_user: 1,
id_thread: 1,
comment: 'Ini Komentar Pertama',
parent: 0,
created_at: Wed Jun 22 2016 13:36:38 GMT+0700 (WIB),
updated_at: Wed Jun 22 2016 13:36:38 GMT+0700 (WIB),
name: 'fahmy Abdul Aziz',
avatar: '/images/img/avatar/100x100/201661154914.jpg',
}]
}
but I'm tired when I run the script always undefined this is my root script
function rootComment(callback){
var sql = "SELECT a.*, b.name as name, b.avatar as avatar \
FROM forum_commentar a \
JOIN users b ON a.id_user = b.id \
JOIN forumthread c ON a.id_thread = c.idThread \
WHERE a.parent = 0 ORDER BY a.created_at DESC LIMIT 10";
DB.query(sql)
.then(function(result){
var child = '';
for (var i = 0; i < result.length; i++) {
getChild(result[i].id_commentForum, function(err, data){
if(err) console.log(err);
else{
if(typeof result[i].child === 'undefined'){
result[i].child = data;
}
}
});
}
retval.comment = result;
callback(null, retval);
})
.catch(function (err) {
console.log(err);
callback(err);
});
}
And this is getChild Script
function getChild(id, cb){
var sql2 = "SELECT a.*, b.name as name, b.avatar as avatar FROM forum_commentar a \
JOIN users b ON a.id_user = b.id \
JOIN forumthread c ON a.id_thread = c.idThread \
LEFT JOIN forum_commentar d ON a.id_commentForum = d.parent \
WHERE a.parent = '"+id+"' ORDER BY a.created_at DESC LIMIT 10";
DB.query(sql2)
.then(function(result){
return cb(null, result);
})
.catch(function (err) {
return cb(err, null);
});
}
the error always [TypeError: Cannot read property 'child' of
undefined]
It seems that the result of DB.query(sql2) is undefined.
you check if result[i].child === 'undefined', but result is undefined.
but I running console.log in this position of code
function rootComment(callback){
var sql = "SELECT a.*, b.name as name, b.avatar as avatar \
FROM forum_commentar a \
JOIN users b ON a.id_user = b.id \
JOIN forumthread c ON a.id_thread = c.idThread \
WHERE a.parent = 0 ORDER BY a.created_at DESC LIMIT 10";
DB.query(sql)
.then(function(result){
var child = '';
for (var i = 0; i < result.length; i++) {
getChild(result[i].id_commentForum, function(err, data){
if(err) console.log(err);
else{
// show the data of getChild()
console.log(data)
}
});
}
retval.comment = result;
callback(null, retval);
})
.catch(function (err) {
console.log(err);
callback(err);
});
}
this is result via command line
{
id_commentForum: 3,
id_user: 2,
id_thread: 1,
comment: 'Ini anak komentar pertama',
parent: 1,
created_at: Wed Jun 22 2016 14:01:51 GMT+0700 (WIB),
updated_at: Wed Jun 22 2016 14:01:51 GMT+0700 (WIB),
name: 'dr. Boyke Dian Nugraha SpOG, MARS.',
avatar: '/images/img/avatar/25x25/avatar.jpg'
}
Related
I had posted this question earlier but someone deleted with How can I access and process nested objects, arrays or JSON?
as possible answer. This is not helping me since a) The key 'date' is spread across several names, b)The objects comprises on arrays & objects & c) The depth at which the key 'date' is present can change.
Hence posting the question again.
I have a JS object as below
const bb = {
Harry: {
details: [
{
cat: "Life",
values: [
{
date: "2021-08-02",
level: 77.6,
},
{
date: "2021-08-03",
level: 79.1,
},
],
},
],
},
Barry: {
details: [
{
cat: "Logic",
values: [
{
date: "2021-08-02",
level: 77.6,
},
{
date: "2021-08-03",
level: 79.1,
},
],
},
],
},
};
I also have a variable defined for parsing the dates const dateParse = d3.timeParse("%Y-%m-%d")
I want to parse all the dates in the object. Since the 'date' is few levels below in the object, I am not able to figure this out. How do I go about it?
The expected output is
const bb = {
Harry: {
details: [
{
cat: "Life",
values: [
{
date: Mon Aug 02 2021 00:00:00 GMT+0530 (India Standard Time),
level: 77.6,
},
{
date: Tue Aug 03 2021 00:00:00 GMT+0530 (India Standard Time),
level: 79.1,
},
],
},
],
},
Barry: {
details: [
{
cat: "Logic",
values: [
{
date: Mon Aug 02 2021 00:00:00 GMT+0530 (India Standard Time),
level: 77.6,
},
{
date: Tue Aug 03 2021 00:00:00 GMT+0530 (India Standard Time),
level: 79.1,
},
],
},
],
},
};
You just have to loop through the objects, select the date node and execute
(new Date(datestring)).toString()
This will generate the date as specified in your output.
const bb = { Harry: { details: [{cat: "Life",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]},Barry: {details: [{cat: "Logic",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]}};
Object.values(bb).forEach((value) => {
value.details.forEach((detail) => {
detail.values.forEach((value) => {
value.date = (new Date(value.date)).toString();
})
})
});
console.log(bb);
If you want to parse all the nested date keys, you can do it recursively using the below functions
const bb = { Harry: { details: [{cat: "Life",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]},Barry: {details: [{cat: "Logic",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]}};
function traverseArray(inputArray) {
for (const arrayValue of inputArray) {
traverseObject(arrayValue);
}
}
function traverseObject(inputObject) {
for (const key in inputObject) {
const value = inputObject[key];
const valueType = typeof(value);
if (valueType == "object") {
traverseObject(value);
} else if (valueType == "array") {
traverseArray(value);
} else if (key == "date") { // since I want to parse only date keys
inputObject[key] = 'd3.timeParse("%Y-%m-%d") - Parse date here';
}
}
}
traverseObject(bb);
console.log(bb);
I am trying to parse JSON but it keeps returning
Uncaught SyntaxError: Unexpected token & in JSON at position 1
at JSON.parse (<anonymous>)
The code looks like this in VS Code:
var result = '{{ bans }}';
var res = JSON.parse(result)
But in the consol it looks like:
var result = '{'bans': [{'appealable': False, 'banend': 'Fri, 15 Jan 2021 00:00:00 GMT', 'bannedby': 'parker02311', 'banstart': 'Fri, 15 Jan 2021 00:18:58 GMT', 'id': 1, 'images': 'https://cdn.discordapp.com/attachments/642127559600898058/799867505727504464/Roblox_1_15_2021_11_07_09_PM_2.png,https://cdn.discordapp.com/attachments/642127559600898058/799863972915314688/Roblox_1_15_2021_10_53_30_PM_2.png', 'notes': '<p>test</p>', 'reasons': 'Chat Bypassing, Discrimination', 'userid': '17', 'username': 'test'}, {'appealable': False, 'banend': 'Wed, 20 Jan 2021 00:00:00 GMT', 'bannedby': 'parker02311', 'banstart': 'Sat, 16 Jan 2021 05:46:33 GMT', 'id': 2, 'images': 'https://image.prntscr.com/image/DUQMlOEKTuGDHSkvB4NuRQ.png,https://cdn.discordapp.com/attachments/642127559600898058/799874004457488394/unknown.png', 'notes': '', 'reasons': 'Chat Bypassing,Discrimination', 'userid': '202181894', 'username': 'Dagdoubleagaming'}]}';
var res = JSON.parse(result)
I am not sure where all the ''s came from because the backend looks like:
r = requests.get('http://localhost:5001/get/bans', timeout=5)
if r.status_code == 200:
jsonre = r.json()
return render_template('index.html', name=current_user.username, title='Dashboard', breadcrums=True, bans=jsonre)
The request returns:
{
"bans": [
{
"appealable": false,
"banend": "Fri, 15 Jan 2021 00:00:00 GMT",
"bannedby": "parker02311",
"banstart": "Fri, 15 Jan 2021 00:18:58 GMT",
"id": 1,
"images": "https://cdn.discordapp.com/attachments/642127559600898058/799867505727504464/Roblox_1_15_2021_11_07_09_PM_2.png,https://cdn.discordapp.com/attachments/642127559600898058/799863972915314688/Roblox_1_15_2021_10_53_30_PM_2.png",
"notes": "<p>test</p>",
"reasons": "Chat Bypassing, Discrimination",
"userid": "17",
"username": "test"
},
{
"appealable": false,
"banend": "Wed, 20 Jan 2021 00:00:00 GMT",
"bannedby": "parker02311",
"banstart": "Sat, 16 Jan 2021 05:46:33 GMT",
"id": 2,
"images": "https://image.prntscr.com/image/DUQMlOEKTuGDHSkvB4NuRQ.png,https://cdn.discordapp.com/attachments/642127559600898058/799874004457488394/unknown.png",
"notes": "",
"reasons": "Chat Bypassing,Discrimination",
"userid": "202181894",
"username": "Dagdoubleagaming"
}
]
}
var result = '{{ bans | escapejs }}'
Just taking a shot here, but I took a look here "https://www.w3schools.com/Js/js_json_parse.asp" and I think this might work. I don't think the string is in json format that's why you're getting the error.
var result = '{"bans"}';
var res = JSON.parse(result)
I'm referring to this answer again.
var firstEvents = events.reduce(function(ar, e) {
var id = e.getId();
if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
ar.push({eventTitle: e.getTitle(), eventId: id, startDate: e.getAllDayStartDate(), endDate: e.getAllDayEndDate()});
}
return ar;
}, []);
What do I have to change to get an array with the event titles (Strings) as keys and the start dates (Date objects) as values so I can retrieve a certain start date (Date object) via firstEvents['some event title']?
EDIT:
Current Ouput:
firstEvents = [{eventTitle=Event title 1, eventId=xyz1#google.com, startDate=Sun Mar 18 00:00:00 GMT+01:00 2018, endDate=Mon Mar 19 00:00:00 GMT+01:00 2018},
{eventTitle=Event title 2, eventId=xyz2#google.com, startDate=Tue Mar 19 00:00:00 GMT+01:00 2019, endDate=Wed Mar 20 00:00:00 GMT+01:00 2019},
{eventTitle=Event title 3, eventId=xyz3#google.com, startDate=Fri Mar 20 00:00:00 GMT+01:00 2020, endDate=Sat Mar 21 00:00:00 GMT+01:00 2020}]
Needed Output (Pseudo):
firstEvents = ['Event title 1' => Sun Mar 18 00:00:00 GMT+01:00 2018,
'Event title 2' => Tue Mar 19 00:00:00 GMT+01:00 2019,
'Event title 3' => Fri Mar 20 00:00:00 GMT+01:00 2020]
Do not use push, but set to object with key.
ar = {}; // You may need to change source parameter too
// you cannot change input Array [] to Object {} type inside function
// you can get Array and return Object, but source variable will not change
ar[e.getTitle()] = e.getAllDayStartDate();
Or using some demo data:
var ar = [
{
eventTitle: 'one',
eventId: '#1',
startDate: new Date(),
endDate: new Date()
},
{
eventTitle: 'two',
eventId: 'secondId',
startDate: new Date(),
endDate: new Date()
}];
var retVal = {};
for (var i of ar) {
retVal[i.eventId] = i;
}
console.log(JSON.stringify(retVal, null, 2));
console.log(retVal['#1']);
console.log(retVal.secondId);
I'm struggling with sorting two levels. The logic is as follows. If any of the objects have a status, return the most recent object with a status. If none of the objects have a status, return the most recent object without a status.
var apps = [
{ status: 'PASS',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
},
{ status: 'FAIL',
date_created: Thu Sep 02 2015 17:24:45 GMT-0700 (PDT),
},
{ status: '',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT),
}
]
var desired_result = [{ status: 'PASS',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
}]
var apps_2 = [
{ status: '',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
},
{ status: '',
date_created: Thu Sep 02 2015 17:24:45 GMT-0700 (PDT),
},
{ status: '',
date_created: Thu Sep 01 2015 17:24:45 GMT-0700 (PDT),
}
]
var desired_resul2 = [{ status: '',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
}]
I've tried
var sorted = _.sort_by(apps, function (x) { x.date_updated });
I've also looked a few other SO questions but can't keep the objects in place after the first sort.
If I understand your question correctly, here is what you are looking for. http://jsfiddle.net/whxu5sea/3/
You need to filter the elements to ensure they have a status of ANY kind. Then sort them by date, earliest first. Then get that first value. In my example I assumed the dates where strings, but still should work.
var apps = [
{ status: 'PASS',
date_created: 'Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)'
},
{ status: 'FAIL',
date_created: 'Thu Sep 02 2015 17:24:45 GMT-0700 (PDT)',
},
{ status: '',
date_created: 'Thu Sep 01 2015 17:24:45 GMT-0700 (PDT)',
}
];
var x;
var arr = _.filter(apps, function(data) {
return !!data.status.length;
});
x = _.chain( arr.length ? arr : apps )
.sortBy(function(data) {
return new Date(data.date_created).getTime();
}).last().value();
console.log( x );
To check if it works when no status is provided: http://jsfiddle.net/whxu5sea/4/
I hope this helps. LMK if any further clarification is needed.
EDIT: Updated to get NEWEST element (last).
Here is a simple solution that iterates just once through apps, without a filtering step. See here for a jsfiddle.
The concept is that, if status is falsy, its date is converted into a negative number that retains the correct sort order among all falsy elements, but makes all falsy elements have a lower sort order than all non-falsy ones.
We convert the falsy element dates by subtracting 8640000000000001, which is (the maximimum millis in a Date, plus one).
var x = _.chain(apps).sortBy(function(x) {
var date = new Date(x.date_created).getTime();
return x.status ? date : date - 8640000000000001;
}).last().value();
console.log( x );
please take a look and let me know why the loop's output is not correct?
Basically I am looping through the friendId array of a user and through the user results for a search and seeing if they match up, depending on the match it should return true or false.
Here is my code for the loop:
User.findById(req.signedCookies.userid, function(err, signedInUser) {
//console.log(JSON.stringify(signedInUser.friendRequest));
for (var x = 0; x < users.length; x++) {
users[x].isFriend = false;
//console.log(users[x].lastName);
for (var i = 0; i < signedInUser.friendRequest.length; i++) {
// console.log(users[x]._id + ' - ' + signedInUser.friendRequest[i].friendId);
//console.log(users[x].isFriend);
if (users[x]._id === signedInUser.friendRequest[i].friendId) {
users[x].isFriend = true;
console.log('test');
break;
}
}
}
res.render('searchResults', {
title: 'Weblio',
userAdded: users
});
});
Output of console.log:
[{"friendId":"51ee2017c2023cc816000002","read":0,"date_requested":"2013-07-23T06
:29:39.021Z"},{"friendId":"51ee203cc2023cc816000003","read":0,"date_requested":"
2013-07-23T06:42:37.872Z"}]
Jones
51ee2017c2023cc816000002 - 51ee2017c2023cc816000002
false
51ee2017c2023cc816000002 - 51ee203cc2023cc816000003
false
Macks
51ee203cc2023cc816000003 - 51ee2017c2023cc816000002
false
51ee203cc2023cc816000003 - 51ee203cc2023cc816000003
false
The signed in user is John Smith and he searched for Jake
Users:
John Smith id ends in 01
Jake Jones ends in 02
Jake Macks ends in 03
Where in fact Jake Macks is in the friendId
console.log('test');
is not being outputed, so I am assuming it is not even going into the if statement of the nested loop
Here is the inputs for these console logs I called right before the console log you moved:
console.log(users);
console.log(signedInUser);
console.log(users[x].isFriend);
The results are:
[ { firstName: 'Jake',
lastName: 'Jones',
email: 'test2#gmail.com',
password: '$2a$10$3ndDWiqOsyN.WN19fKJqq.xiC0B9da7QKTL74995zCT8vHrClo2uW',
phone: 98439843943,
birthday: Mon Jun 04 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
_id: 51ee2017c2023cc816000002,
__v: 0,
friend: [],
friendRequest: [] },
{ firstName: 'Jake',
lastName: 'Macks',
email: 'test3#gmail.com',
password: '$2a$10$XTsGrWmmOH/3O3eNwrNK2u.XOwl5cPPGyKrzgU0RMROcGTtU1LkDK',
phone: 49372432922,
birthday: Mon Jun 04 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
_id: 51ee203cc2023cc816000003,
__v: 0,
friend: [],
friendRequest: [] } ]
{ __v: 0,
_id: 51ee1ddbc2023cc816000001,
birthday: Mon Aug 06 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
email: 'test1#gmail.com',
firstName: 'John',
lastName: 'Smith',
password: '$2a$10$w6jTLvW.gUW5tY59/2/vIu8XPVsOe/NTr3e.Qc0WvVKIG8/MwSDW.',
phone: 1122334422,
friend: [],
friendRequest:
[ { date_requested: Tue Jul 23 2013 02:29:39 GMT-0400 (Eastern Daylight Time)
,
read: 0,
friendId: 51ee2017c2023cc816000002 },
{ date_requested: Tue Jul 23 2013 02:42:37 GMT-0400 (Eastern Daylight Time)
,
read: 0,
friendId: 51ee203cc2023cc816000003 } ] }
false
[ { firstName: 'Jake',
lastName: 'Jones',
email: 'test2#gmail.com',
password: '$2a$10$3ndDWiqOsyN.WN19fKJqq.xiC0B9da7QKTL74995zCT8vHrClo2uW',
phone: 98439843943,
birthday: Mon Jun 04 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
_id: 51ee2017c2023cc816000002,
__v: 0,
friend: [],
friendRequest: [] },
{ firstName: 'Jake',
lastName: 'Macks',
email: 'test3#gmail.com',
password: '$2a$10$XTsGrWmmOH/3O3eNwrNK2u.XOwl5cPPGyKrzgU0RMROcGTtU1LkDK',
phone: 49372432922,
birthday: Mon Jun 04 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
_id: 51ee203cc2023cc816000003,
__v: 0,
friend: [],
friendRequest: [] } ]
{ __v: 0,
_id: 51ee1ddbc2023cc816000001,
birthday: Mon Aug 06 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
email: 'test1#gmail.com',
firstName: 'John',
lastName: 'Smith',
password: '$2a$10$w6jTLvW.gUW5tY59/2/vIu8XPVsOe/NTr3e.Qc0WvVKIG8/MwSDW.',
phone: 1122334422,
friend: [],
friendRequest:
[ { date_requested: Tue Jul 23 2013 02:29:39 GMT-0400 (Eastern Daylight Time)
,
read: 0,
friendId: 51ee2017c2023cc816000002 },
{ date_requested: Tue Jul 23 2013 02:42:37 GMT-0400 (Eastern Daylight Time)
,
read: 0,
friendId: 51ee203cc2023cc816000003 } ] }
false
One problem you have is the location where you are attempting to log the result of isFriend. It's currently being logged just after you set isFriend to false as you enter the search loop.
That statement needs to be moved just after the inner for loop.
Without having all of the inputs, it makes it very difficult to guess where the problem might be.
Using the following as input (Can you provide what the actual input is in JSON format?):
var users = [
{
lastName: 'Smith',
'_id': "51ee2017c2023cc816000001"
},
{
lastName: 'Jones',
'_id': "51ee2017c2023cc816000002"
},
{
lastName: 'Macks',
'_id': "51ee2017c2023cc816000003"
}
];
var signedInUser = {
friendRequest: [{
"friendId": "51ee2017c2023cc816000002",
"read": 0,
"date_requested": "2013-07-23T06:29:39.021Z"
}, {
"friendId": "51ee203cc2023cc816000003",
"read": 0,
"date_requested": "2013-07-23T06:42:37.872Z"
}]
};
function test(err, signedInUser) {
console.log("\nsignedInUser.friendRequest\n" + JSON.stringify(signedInUser.friendRequest, null, 2));
for (var x = 0; x < users.length; x++) {
users[x].isFriend = false;
console.log("\n" + users[x].lastName);
for (var i = 0; i < signedInUser.friendRequest.length; i++) {
console.log(users[x]._id + ' - ' + signedInUser.friendRequest[i].friendId);
if (users[x]._id === signedInUser.friendRequest[i].friendId) {
users[x].isFriend = true;
console.log('test');
break;
}
}
console.log(users[x].isFriend);
}
console.log("\nFinal users:\n" + JSON.stringify(users, null, 2));
}
test(null, signedInUser);
I see the following results:
signedInUser.friendRequest
[
{
"friendId": "51ee2017c2023cc816000002",
"read": 0,
"date_requested": "2013-07-23T06:29:39.021Z"
},
{
"friendId": "51ee203cc2023cc816000003",
"read": 0,
"date_requested": "2013-07-23T06:42:37.872Z"
}
]
Smith
51ee2017c2023cc816000001 - 51ee2017c2023cc816000002
51ee2017c2023cc816000001 - 51ee203cc2023cc816000003
false
Jones
51ee2017c2023cc816000002 - 51ee2017c2023cc816000002
test
true
Macks
51ee2017c2023cc816000003 - 51ee2017c2023cc816000002
51ee2017c2023cc816000003 - 51ee203cc2023cc816000003
false
Final users:
[
{
"lastName": "Smith",
"_id": "51ee2017c2023cc816000001",
"isFriend": false
},
{
"lastName": "Jones",
"_id": "51ee2017c2023cc816000002",
"isFriend": true
},
{
"lastName": "Macks",
"_id": "51ee2017c2023cc816000003",
"isFriend": false
}
]
Other than the log statement being in the wrong place (I don't think I changed the semantics of your code), with this set of inputs, the logic works. It is likely the input you were expecting is not what you are receiving.
It turns out the OP was using the mongoose native driver for nodejs and, after researching found the answer to the comparison portion of the problem here: Comparing mongoose _id and strings
I'd suggest comparing VALUES, not OBJECTS - use ==, not ===, based on this:
Why Array.indexOf doesn't find identical looking objects
This is a wild guess, but I suspect you are attempting to return the value here:
res.render('searchResults', {title: 'Weblio', userAdded: users });
If so, user added will have the users collection under userAdded, not a true/false.
You might need to set a boolean value to true (e.g. myVariable = true) when you break of the loop and use that variable as your return value.