Loop is not outputting true or false based on query - javascript

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.

Related

Javascript array of multiple object

How to convert the 1 object with multiple item inside to an array of object? please see the picture below to understand what i meant, thanks
var author = (`SELECT author, title, remarks, status, date FROM Transaction`, 1000, data=>{
let obj = {[author: [], book: [], condition: [], status: [], date: []]}
for(let x = 0; x < data.length; x++){
obj.author.push(data[x][0]);
obj.book.push(data[x][1]);
obj.condition.push(data[x][2]);
obj.status.push(data[x][3]);
obj.date.push(data[x][4]);
}
console.log("obj: ", obj)
return resolve(obj);
})
The Current result of console.log("obj: ", obj)
{
"authors": "testuser,testname",
"books": "440936785,440936694",
"conditions": "Very Good,New,",
"status": "Not Available,Available",
"datepublished": "Mon Mar 28 2022 18:42:24 GMT+0800 (Philippine Standard Time),Mon Mar 28 2022 18:42:39 GMT+0800 (Philippine Standard Time)"
}
What I want result:
{
"authors": "testname",
"books": "440936694",
"conditions": "New",
"status": "Available",
"datepublished": "Mon Mar 28 2022 18:42:24 GMT+0800 (Philippine Standard Time)"
},
{
"authors": "testname",
"books": "440936694",
"conditions": "New,",
"status": "Available",
"datepublished": "Mon Mar 28 2022 18:42:39 GMT+0800 (Philippine Standard Time)"
}
You have a list of rows and want to create a list of objects. That means you have to convert every row to an object. Such a transformation is typically done with Array#map, which applies a function to every element in an array a produces a new array from the return value of that function:
const objects = data.map(row => ({
author: row[0],
book: row[1],
condition: row[2],
status: row[3],
date: row[4],
}));
The library you are using to query the database might also be able to already create an object per row (using the column names) so you don't have to do the mapping yourself.

map on the lower level key of a nested object

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);

Angularjs, update values in an Array

This is my array
someArray = [
{
city: colombo1,
text: 'name1',
newArray[ date: 2018-09-29T18:30:00.000Z, discription: 'none']
}
{
city: colombo2,
text: 'name',
newArray[ date: 2018-10-10T07:03:43.835Z, discription: 'none']
}
];
I want to update my array as below
someArray = [
{
city: colombo1,
text: 'name1',
newArray[ date: Sun Sep 30 2018 00:00:00 GMT+0530 (India Standard Time), discription: 'none']
}
{
city: colombo2,
text: 'name',
newArray[ date: Wed Oct 10 2018 14:05:27 GMT+0530 (India Standard Time), discription: 'none']
}
];
I try to use map() to update my array. But I cannot understand the logic to do that. Can anyone please help me. Thank you
i hope newArray is an array which has 'date' as index,
for(var i=0;i<someArray.length;i++){
someArray[i].newArray['date'] = new Date(someArray[i].newArray['date']).toString();
}
If you want use map try something like this:
var mappedArray = someArray.map(function(item){
item.newArray['date'] = convertDate(item.newArray['date']);
});
https://jsfiddle.net/83sqfxc0/1/

How make comment system nodejs + mysql

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'
}

Javascript sorting with two properties

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 );

Categories