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);
This is my Array
$scope.tooltipsArray = [
{
date: 2018-10-10T07:03:43.835Z,
text: 'name1'
},
{
date: 2018-09-29T18:30:00.000Z,
text: 'name2'
}
];
How can I update date to locale date format like this.
$scope.tooltipsArray = [
{
date: Wed Oct 10 2018 14:05:27 GMT+0530 (India Standard Time),
text: 'name1'
},
{
date: Sun Sep 30 2018 00:00:00 GMT+0530 (India Standard Time),
text: 'name2'
}
];
I have used map() to do that. But it does not work
var vector = $scope.tooltipsArray.map(function (el) { return new Date(el.date).toLocaleDateString(); });
Can anyone tell me how to do this from map() in JavaScript?
You can use the below code -
$scope.tooltipsArray = [
{
date: "2018-10-10T07:03:43.835Z",
text: 'name1'
},
{
date: "2018-09-29T18:30:00.000Z",
text: 'name2'
}
];
var vector = $scope.tooltipsArray.map(function(el) {return { 'date':new Date(el.date).toString(),'text':el.text}});
console.log(vector);
The output will be like below -
[
{date: "Wed Oct 10 2018 12:33:43 GMT+0530 (India Standard Time)", text: "name1"}
{date: "Sun Sep 30 2018 00:00:00 GMT+0530 (India Standard Time)", text: "name2"}
]
Why is there a .value key after tooltipsArray?
You assigned the array to tooltipsArray, so unless there's a Proxy involved, expect to access the array through $scope.tooltipsArray.
To fix it, just remove .value.
var vector = $scope.tooltipsArray.map(function (el) { return new Date(el.date).toLocaleDateString(); });
1- Remove .value why is there in the first place?
2- You need to change the date inside the object and then return el instead of date if you just want the date to be changed, likewise:
var vector = $scope.tooltipsArray.map(function(el) {
el.date = new Date(el.date).toLocaleDateString();
return el;
});
What map function does is going through array element one by one and run the callback function, so what you have to do is update the whole object or update one entry
el.date = new Date(el.date).toLocaleDateString();
I'm attempting to use underscore to filter out certain properties of an object. The beginning of the following code works as expected, but .pick is not working. I'm aiming to limit the properties of the returned object to those strings listed in the .pick method.
var result = _.chain(data)
.each(function(item) {
item.answers = [];
_.each(data, function(object) {
if (item.id === object.id) {
item.answers.push({
id: object.answer_id,
email: object.answer_email,
date: object.answer_date
});
}
});
item = _.pick(item,
'id',
'owner_id',
'url',
'enabled',
'review_date',
'answers'
);
})
.uniq(function(item) {
return item.id;
})
.value();
The array I start with, 'data', looks like this:
[
{
id: '8ffdf27b-5a90-478a-b263-dhhdhdhhdhd',
answer_date: Fri Oct 30 2015 14:35:07 GMT-0400 (EDT),
answer_id: 1,
answer_email: 'test#example.com',
owner_id: 5,
url: 'media/5-4a3640ac-ec13-fhhfh-ac0a-fhjhdhhdhd.jpg',
enabled: false,
review_date: Sun Nov 01 2015 13:57:32 GMT-0500 (EST)
}, ...
]
The returned array 'should' look like so:
[
{
id: '8ffdf27b-5a90-478a-b263-dhhdhdhhdhd',
owner_id: 5,
url: 'media/5-4a3640ac-ec13-fhhfh-ac0a-fhjhdhhdhd.jpg',
enabled: false,
review_date: Sun Nov 01 2015 13:57:32 GMT-0500 (EST),
answers: [{...}, {...}]
}, ...
]
but instead currently looks like this:
[
{
id: '8ffdf27b-5a90-478a-b263-dhhdhdhhdhd',
answer_date: Fri Oct 30 2015 14:35:07 GMT-0400 (EDT),
answer_id: 1,
answer_email: 'test#example.com',
owner_id: 5,
url: 'media/5-4a3640ac-ec13-fhhfh-ac0a-fhjhdhhdhd.jpg',
enabled: false,
review_date: Sun Nov 01 2015 13:57:32 GMT-0500 (EST),
answers: [{...}, {...}]
}, ...
]
You should use map() instead of each() to change your array (note that you have to return the modified item in the map function):
var result = _.chain(data)
.map(function (item) {
item.answers = [];
_.each(data, function (object) {
if (item.id === object.id) {
item.answers.push({
id: object.answer_id,
email: object.answer_email,
date: object.answer_date
});
}
});
item = _.pick(item,
'id',
'owner_id',
'url',
'enabled',
'review_date',
'answers'
);
return item;
})
.uniq(function (item) {
return item.id;
})
.value();
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.