Node.js - Access key from object - javascript

I try to access a key from an object I get back from an API but when I do so, I get the key of the object in a strange format.
This is what I get when I console.log the object (booking):
{ createdDate: 2018-03-26T11:36:09.694Z,
date: 2018-03-26T13:45:00.000Z,
...,
vouchers:
List [
{ value: 100,
code: 'vouchercode',
...
}
]
}
When I then try to console.log the "vouchers" key:
booking.vouchers
I get this:
{ [Function: f]
_receiver: {
createdDate: 2018-03-26T11:36:09.694Z,
date: 2018-03-26T13:45:00.000Z,
...,
vouchers: List [ [Object] ] },
_scope:
{ where: { bookingId: 5ab8db29b24991b50704445a },
collect: 'voucher',
include: 'voucher' },
_targetClass: 'Voucher',
find: [Function],
getAsync: [Function],
...,
}
Why do I get it in this format and how do I convert it to a normal object like this?:
vouchers: [
{ value: 100,
code: 'vouchercode',
...
}
]
I hope the problem is understandable and some of you can help :)
Edit:
This is my code:
Booking.findById id, {include:[ 'vouchers']}, (err, booking)->
console.log booking
vouchers = booking.vouchers
console.log vouchers
*Note: I know this is coffeescript but I don't think thats the problem

Related

Calling a JSON key that has a non-letter character

I am trying to return the value of #microsoft.graph.downloadUrl from the json object below:
[
{
'#microsoft.graph.downloadUrl': 'https://public.bl.files.1drv.com/XXXX',
createdDateTime: '2021-07-10T06:14:31.03Z',
cTag: 'QQQQ',
eTag: 'SSSS',
id: 'FFFF',
lastModifiedDateTime: '2021-07-12T09:27:21.69Z',
name: 'FILE_NAME',
size: 98580,
webUrl: 'https://1drv.ms/b/SSSS',
reactions: { commentCount: 0 },
createdBy: { application: [Object], user: [Object] },
lastModifiedBy: { user: [Object] },
parentReference: {
driveId: 'XXX',
driveType: 'personal',
id: 'YYYY!YYY',
name: 'Documents',
path: '/drive/root:/Documents'
},
file: { mimeType: 'application/pdf', hashes: [Object] },
fileSystemInfo: {
createdDateTime: '2021-07-10T06:14:31.03Z',
lastModifiedDateTime: '2021-07-12T09:27:21.69Z'
}
}
]
I wish to use something like this that i had done to extract the name as I need to be able to get the #microsoft.graph.downloadUrl from each json object (known as f below) in 'files'.
var fileName = (JSON.stringify(files[f].name));
I tried both:
var fileURL = (JSON.stringify(files[f]."#microsoft.graph.downloadUrl"));
var fileURL = (JSON.stringify(files[f].#microsoft.graph.downloadUrl));
but neither work -- any help would be much appreciated!
You should just use files[f]["#microsoft.graph.downloadUrl"].

Storing data from JSON object received from Google People Api

So I have a server that receives data from Google People api regarding contacts and my received object has the following structure:
{ connections:
[ { resourceName: 'people/c3904925882068251400',
etag: '%EgYBAgkLNy4aDQECAwQFBgcICQoLDA0iDFZUOUE0NkRBZW0wPQ==',
names:
[ { metadata: { primary: true, source: [Object] },
displayName: 'Mihai Vrincut',
familyName: 'Vrincut',
givenName: 'Mihai',
displayNameLastFirst: 'Vrincut, Mihai' },
{ metadata: { source: [Object] },
displayName: 'Mihai Vrincut',
familyName: 'Vrincut',
givenName: 'Mihai',
displayNameLastFirst: 'Vrincut, Mihai' } ],
emailAddresses:
[ { metadata: { primary: true, source: [Object] },
value: 'mihai.vrincut#gmail.com' } ] },
{ resourceName: 'people/c3275206487406036814',
etag: '%EgYBAgkLNy4aDQECAwQFBgcICQoLDA0iDHBFVzBUMm8wWU5nPQ==',
names:
[ { metadata: { primary: true, source: [Object] },
displayName: 'aaaaaaaaa',
givenName: 'aaaaaaaaa',
displayNameLastFirst: 'aaaaaaaaa' } ] },
{ resourceName: 'people/c5777943907795350059',
etag: '%EgYBAgkLNy4aDQECAwQFBgcICQoLDA0iDGxOeGYwblg3bFUwPQ==',
names:
[ { metadata: { primary: true, source: [Object] },
displayName: 'costin',
givenName: 'costin',
phoneticFamilyName: 'cancius',
phoneticGivenName: 'costin',
displayNameLastFirst: 'costin' } ],
emailAddresses: [ { metadata: { primary: true, source: [Object] }, value: 'hj' } ],
phoneNumbers:
[ { metadata: { primary: true, source: [Object] },
value: '07543532512',
canonicalForm: '+40754353251' } ] } ], totalPeople: 3}totalItems: 3 }
In order to get this object I used the util.inspect() method. However, when I try to access the names for example, I get undefined:
var response=util.inspect(responses,{depth:5});
Console.log(response.connections[0].names);
What is wrong?
So, given the situation, and the information you've given over the comment sections.
I assume that responses is already an object, but util.inspect, makes it a string with a JSON kind of syntax but without the quotes (") before and after the names of the keys. That's why you get
{ connections: ^ SyntaxError: Unexpected token c in JSON at position 2
So, try going over the responses object.
console.log(responses)
And get the name of the keys. With them
console.log(responses.sth.sthElse.anotherSth.anotherSthElse.lastSth.connections)
And see if you get the expected result :)
You should convert the response to JSON Object.
try this:
console.log(JSON.parse(response).connections[0].names);
(I am assuming you are working in Javascript)
What I would do is validate if the answer is a String, you have a
console.log (typeof response)
if it is a string, convert it to JSON:
let responseObject = JSON.parse (response);
Finally, try if you can access the object:
console.log (responseObject.connections [0] .names);
You tell me your answer :)

How to iterate thru multiple values in a single key in mongoose

I have a web app which uses MongoDB as database and I'm trying to iterate thru multiple values inside a single property named passport.
This is my schema:
var EmployeeDBSchema = new Schema({
/* Passport tab schema */
passportInfo: {
passportDetails: []
},
And here's how it looks in Robomongo:
I tried checking if this can be retrieved as an array, so I did below:
console.log(_.map(results, _.property('passportInfo')));
passportArr = _.map(results, _.property('passportInfo'));
console.log("is passport array? " + _.isArray(passportArr));
Result:
Now since it was positive, I tried iterating thru it like a normal array using the ff. code:
_.forEach(passportArr, function (value, key) {
_.forEach(passportArr[key], function(value2, key2){
console.log(key2 + " >> " + value2);
});
});
However, what I got was this:
How can I get the values of passportExpiry, passportNumber and countryOfOrigin?
I'm really having a hard time over this. Hoping somebody can help.
Thank you.
EDIT: Not sure if this will help but, I got the idea for the structure from this Plunker. Main idea behind Passport was the user can add an unlimited number of passport information (hence the passportInfo array). I'm trying to retrieve the data here so I can render it as a CSV file.
UPDATE:
Here's the expanded results as requested (from console.log):
full results
[ { _id: dummyiddontmind123,
employeeID: '123asd12',
desiredRoleOther: 'Other role',
desiredRole3: 'Role 3',
desiredRole2: 'Role 2',
desiredRole1: 'The Role',
isOpenToIntlAssignment: 'Y',
employeeName: 'Jane Doe',
yrsInIT: 1,
visaInfo:
[ { visaCountryOfOrigin: [Object],
visaNumber: 'asd',
visaEntry: 'Single',
visaExpiry: '2017-03-16T16:00:00.000Z',
visaStatus: 'expired' } ],
passportInfo:
[ { countryOfOrigin: [Object],
passportNumber: [Object],
passportExpiry: '2017-03-03' },
{ countryOfOrigin: [Object],
passportNumber: [Object],
passportExpiry: '2017-03-08T16:00:00.000Z' },
{ countryOfOrigin: [Object],
passportNumber: [Object],
passportExpiry: '2017-03-10T16:00:00.000Z' } ] } ]
[ [ { passportExpiry: '2017-03-03',
passportNumber: { '0': 'EB1234567' },
countryOfOrigin: { '0': 'Philippines' } },
{ passportExpiry: '2017-03-08T16:00:00.000Z',
passportNumber: { '1': 'AS1234' },
countryOfOrigin: { '1': 'Japan' } },
{ passportExpiry: '2017-03-10T16:00:00.000Z',
passportNumber: { '2': 'AX123' },
countryOfOrigin: { '2': 'Singapore' } } ] ]
Your data inside passportInfo is a bit off, probably due to some copy-paste error after outputting it.
I take it you want to export all stored passport information into a csv of format country; number; expiry.
The first thing you want to make sure is that the actual data and the data you expect are structurally the same. If not, you can still add transformation steps before (e.g. flatten arrays or transform objects from {0: 123} to [123]).
As soon as this is under control, you can start by mapping the objects of employee.passportInfo from a structured object to an array of information necessary for your csv. This happens using Array.prototype.map.
I added another step inside that map to make sure an object of passportInfo.passportNumber of the form {0: 123} is transformed into an array [123]. This array is then used to map to a single line of your csv by adding passportInfo.countryOfOrigin and .passportExpiry.
// The following code snippets only operates on one employee. If you have an array use an iteration function depending on your needs.
const employee = { _id: 123,
employeeID: '123asd12',
desiredRoleOther: 'Other role',
desiredRole3: 'Role 3',
desiredRole2: 'Role 2',
desiredRole1: 'The Role',
isOpenToIntlAssignment: 'Y',
employeeName: 'Jane Doe',
yrsInIT: 1,
visaInfo: [ {
visaCountryOfOrigin: [Object],
visaNumber: 'asd',
visaEntry: 'Single',
visaExpiry: '2017-03-16T16:00:00.000Z',
visaStatus: 'expired' }
],
passportInfo: [ {
countryOfOrigin: 'ABC',
passportNumber: { 0: '123123123' },
passportExpiry: '2017-03-03'
}, {
countryOfOrigin: 'DEF',
passportNumber: { 0: '321321321', 1: '123123123' },
passportExpiry: '2017-03-08T16:00:00.000Z'
}, {
countryOfOrigin: 'GHI',
passportNumber: { 0: '654654654' },
passportExpiry: '2017-03-10T16:00:00.000Z'
} ]
};
const flattenPassportNumbers = numbers =>
Object.keys(numbers).map(key => numbers[key]);
const info = employee.passportInfo.map(({passportNumber, passportExpiry, countryOfOrigin}) =>
flattenPassportNumbers(passportNumber).map(number =>
[countryOfOrigin, number, passportExpiry]
)
);
const flattenLine = ([line]) => line;
const joinLine = (line) => line.join('; ');
const lines = info.map(flattenLine);
console.log(lines.map(joinLine));
console.log(lines.map(joinLine).join('\n'));
If there's something you don't understand, please don't hesitate to ask.

How can I remove object from array, with Lodash?

I'm trying to remove an object from an array using Lodash.
In server.js (using NodeJS):
var lodash = require('lodash')();
var rooms = [
{ channel: 'room-a', name: 'test' },
{ channel: 'room-b', name: 'test' }
]
I tried with two commands and it did not work:
var result = lodash.find(rooms, {channel: 'room-a', name:'test'});
var result = lodash.pull(rooms, lodash.find(rooms, {channel: 'room-a', name:'test'}));
Here's the output of console.log(result):
LodashWrapper {
__wrapped__: undefined,
__actions__: [ { func: [Function], args: [Object], thisArg: [Object] } ],
__chain__: false,
__index__: 0,
__values__: undefined }
Can someone help me? Thank you!
_.remove() is a good option.
var rooms = [
{ channel: 'room-a', name: 'test' },
{ channel: 'room-b', name: 'test' }
];
_.remove(rooms, {channel: 'room-b'});
console.log(rooms); //[{"channel": "room-a", "name": "test"}]
<script src="https://cdn.jsdelivr.net/lodash/4.14.2/lodash.min.js"></script>
I'd go for reject() in this scenario. Less code:
var result = _.reject(rooms, { channel: 'room-a', name: 'test' });
require('lodash')()
Calling the lodash function (by ()) creates a LoDash object that wraps undefined.
That's not what you want; you want the lodash function itself, which contains static methods.
Remove that.

How to loop over rows after .fetchAll Bookshelf js + knex js?

I have a MySQL Database which I need to query from node.js
I am using bookshelf and knex for this.
I want to get the contents of a table - I have defined a table in my model.js file. I am attempting the query like this:
//select * from completedSentences;
Model.CompletedSentences.fetchAll().then(function (resData) {
console.log(resData)
})
I would like to know how to loop over resData because it should be multiple rows.
The output of the console looks like this: I dont see a list of rows I can loop over.. What am i missing?
CollectionBase {
model:
{ [Function]
NotFoundError: [Function: ErrorCtor],
NoRowsUpdatedError: [Function: ErrorCtor],
NoRowsDeletedError: [Function: ErrorCtor] },
length: 1,
models:
[ ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c4',
id: 1 } ],
_byId:
{ '1':
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c4',
id: 1 },
c4:
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: {},
cid: 'c4',
id: 1 } },
_knex: null,
_events: {},
_eventsCount: 0 }
I found the answer (the documentation is very cryptic, hope this helps others)
new Model.CompletedSentences().fetchAll().then(function (resData) {
_.each(resData.models, function (model) { //I am looping over models using underscore, you can use any loop
console.log(model.attributes)
})
})
Model.CompletedSentences.fetchAll().then(function (resData) {
console.log(resData.serialize())
})
output is in json format
http://bookshelfjs.org/#Model-instance-serialize
The Collection class has a set of lodash methods for this.
You can use collection.forEach this way:
new Model.CompletedSentences().fetchAll().then(function (completedSentences) {
completedSentences.forEach(function (model) {
console.log(model.attributes)
})
})
Check out the docs, there are many other useful methods for Collection.
If you dont want to use lodash, you can do this:
new Model.CompletedSentences().fetchAll().then(function (resData) {
resData.models.forEach( function (model) {
console.log(model.get('attribute');
console.log(model.related('sth').get('attribute');
})
})
simply just console with it attributes.
console.log(resData.attributes);
you will get results Objects vise.
Answer is simple, try this
console.log(resData.toJSON())

Categories

Resources