I have this code into my app that returns some job feed in json format:
My code looks as below:
JobFeed.find().sort('-created').exec(function (err, feeds) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
_.forEach(feeds, function (row, key) {
console.log(row.data.title); // showing undefined
});
res.jsonp(feeds);
}
});
and the json looks like below:
{ data:
{ isSaved: null,
client:
{ lastContractTitle: null,
feedbackText: '4.78 Stars, based on 13 feedbacks',
paymentVerificationStatus: 1,
lastContractPlatform: null,
totalFeedback: 4.7819242373,
location: [Object],
lastContractRid: 0,
edcUserId: 3728985,
totalReviews: 13,
companyRid: 0,
spentTier: '$7,500+',
companyName: null },
amount: { amount: 0, currencyCode: 'USD' },
createdOn: '2016-10-13T06:30:54+00:00',
skills: [ [Object], [Object], [Object], [Object] ],
enterpriseJob: false,
ciphertext: '~01026b31d972ed826b',
proposalsTier: null,
description: 'Hello! We\'re currently searching for a developer with',
category2: 'Web, Mobile & Software Dev',
type: 2,
tierText: 'Intermediate ($$)',
relevance:
{ hoursInactive: 0,
id: 208660674,
publishTime: '1476340265000',
recommendedEffectiveCandidates: 2,
effectiveCandidates: 3,
uniqueImpressions: 0 },
isApplied: null,
engagement: '30+ hrs/week',
recno: 208660674,
title: 'Server-side and Client-side Game Developer for Indie MMO',
freelancersToHire: 0,
maxAmount: { amount: 0, currencyCode: 'USD' },
duration: 'More than 6 months',
subcategory2: 'Game Development',
sticky: false,
stickyLabel: '',
feedback: null },
id: 57ffcdbf717ca50cf0b4cbc1 }
{ data:
{ isSaved: null,
client:
{ lastContractTitle: null,
feedbackText: 'No feedback yet',
paymentVerificationStatus: 1,
lastContractPlatform: null,
totalFeedback: 0,
location: [Object],
lastContractRid: 0,
edcUserId: 0,
totalReviews: 0,
companyRid: 0,
spentTier: '$100+',
companyName: null },
amount: { amount: 0, currencyCode: 'USD' },
createdOn: '2016-10-13T06:30:51+00:00',
skills: [ [Object], [Object], [Object] ],
enterpriseJob: false,
ciphertext: '~01c59efb9135ed91d0',
proposalsTier: null,
description: 'Hello! We\'re currently searching for a developer with',
category2: 'Web, Mobile & Software Dev',
type: 2,
tierText: 'Entry Level ($)',
relevance:
{ hoursInactive: 0,
id: 208660673,
publishTime: '1476340266000',
recommendedEffectiveCandidates: 18,
effectiveCandidates: 74,
uniqueImpressions: 0 },
isApplied: null,
engagement: 'Less than 10 hrs/week',
recno: 208660673,
title: 'Wordpress & Stripe developer',
freelancersToHire: 0,
maxAmount: { amount: 0, currencyCode: 'USD' },
duration: 'More than 6 months',
subcategory2: 'Web Development',
sticky: false,
stickyLabel: '',
feedback: null },
id: 57ffcdbf717ca50cf0b4cbc2 }
{ data:
{ isSaved: null,
client:
{ lastContractTitle: null,
feedbackText: 'No feedback yet',
paymentVerificationStatus: 5,
lastContractPlatform: null,
totalFeedback: 0,
location: [Object],
lastContractRid: 0,
edcUserId: 0,
totalReviews: 0,
companyRid: 0,
spentTier: 'Less than $100',
companyName: null },
amount: { amount: 2000, currencyCode: 'USD' },
createdOn: '2016-10-13T06:30:18+00:00',
skills: [ [Object], [Object] ],
enterpriseJob: false,
ciphertext: '~0101449f91585e8e16',
proposalsTier: null,
description: 'I need a Christmas card app before 15th Dec.n',
category2: 'Web, Mobile & Software Dev',
type: 1,
tierText: 'Intermediate ($$)',
relevance:
{ hoursInactive: 0,
id: 208660669,
publishTime: '1476340233000',
recommendedEffectiveCandidates: 7,
effectiveCandidates: 52,
uniqueImpressions: 0 },
isApplied: null,
engagement: null,
recno: 208660669,
title: 'Christmas Card iPhone App',
freelancersToHire: 0,
maxAmount: { amount: 0, currencyCode: 'USD' },
duration: null,
subcategory2: 'Mobile Development',
sticky: false,
stickyLabel: '',
feedback: null },
id: 57ffcdbf717ca50cf0b4cbc3 }
{ data:
{ isSaved: null,
client:
{ lastContractTitle: null,
feedbackText: '4.88 Stars, based on 102 feedbacks',
paymentVerificationStatus: 1,
lastContractPlatform: null,
totalFeedback: 4.8843944128,
location: [Object],
lastContractRid: 0,
edcUserId: 0,
totalReviews: 102,
companyRid: 0,
spentTier: '$25,000+',
companyName: null },
amount: { amount: 100, currencyCode: 'USD' },
createdOn: '2016-10-13T06:30:00+00:00',
skills:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ],
enterpriseJob: false,
ciphertext: '~01a04eab3b05372652',
proposalsTier: null,
description: 'Hello! We\'re currently searching for a developer with',
category2: 'Writing',
type: 1,
tierText: 'Entry Level ($)',
relevance:
{ hoursInactive: 0,
id: 208660668,
publishTime: '1476340202000',
recommendedEffectiveCandidates: 2,
effectiveCandidates: 6,
uniqueImpressions: 0 },
isApplied: null,
engagement: null,
recno: 208660668,
title: 'Filipino Blog/Content Writers For a Filipino Site (Using WordPress)',
freelancersToHire: 3,
maxAmount: { amount: 0, currencyCode: 'USD' },
duration: null,
subcategory2: 'Article & Blog Writing',
sticky: false,
stickyLabel: '',
feedback: null },
id: 57ffcdbf717ca50cf0b4cbc4 }
The foreach that I have, seems to iterate through each of items, but there is no way I can get the title for each item. Any Help?
I'm not really sure what you're trying to do, but something like this should work if the data is indeed what you have on your comments:
feeds.forEach(function(feed){
console.log(feed.data.title);
});
If you want faster performance, use the regular for loop. I tested this out on my project. Let me know if this doesn't work.
Related
Say I have a data structure like so.
child: [
{
typeOfPackage: 'subSub',
parents: '/Test123/Diet/',
itemName: '250 ML',
pricePerItem: 150,
quantity: 0,
quantityType: '123',
description: '5',
avgTimeTaken: 0,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
_id: 617f9efdf0347931684888fd
},
{
typeOfPackage: 'sub',
parents: '/Test123/',
itemName: 'Regular',
pricePerItem: 0,
quantity: 0,
quantityType: '1',
description: '1',
avgTimeTaken: 1,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
_id: 617f9efdf0347931684888fe
},
{
typeOfPackage: 'subSub',
parents: '/Test123/Reg3/',
itemName: '500ML',
pricePerItem: 123,
quantity: 0,
quantityType: '12',
description: '123',
avgTimeTaken: 51,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
_id: 617f9efdf0347931684888ff
}
]
I intend to transform this data by splitting parents. And my intended result looks as follows:
child: [
{
itemName: 'Test123',
subPackages: [
{
itemName: 'Diet',
subSubPackages: [{
typeOfPackage: 'subSub',
parents: '/Test123/Diet/',
itemName: '250 ML',
pricePerItem: 150,
quantity: 0,
quantityType: '123',
description: '5',
avgTimeTaken: 0,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
}]
},
{
itemName: 'Regular',
typeOfPackage: 'sub',
parents: '/Test123/',
pricePerItem: 0,
quantity: 0,
quantityType: '1',
description: '1',
avgTimeTaken: 1,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
subSubPackages: [],
},
{
itemName: 'Reg3',
subSubPackages: [
{
typeOfPackage: 'subSub',
parents: '/Test123/Reg3/',
itemName: '500ML',
pricePerItem: 123,
quantity: 0,
quantityType: '12',
description: '123',
avgTimeTaken: 51,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
_id: 617f9efdf0347931684888ff
}
]
},
]
}
]
I tried using lodash's chain and groupBy but I could only get as far as grouping it by the first itemName (Test123). I could not figure out how to do further grouping inside that without using a custom for loop and map methods and that too confused me.
You could split parents and build a nested structure.
This approach takes an shadow object for a faster access to same named parents and returns only the payload without organizing structure.
If you like to use subPackages or subSubPackages, you could take a function for generating this key along with the actuyl nesting level. For later processing data, I recommend to use only generic names, like children for every level.
const
getSub = level => `sub${'Sub'.repeat(level)}Level`,
data = [{ typeOfPackage: 'subSub', parents: '/Test123/Diet/', itemName: '250 ML', pricePerItem: 150, quantity: 0, quantityType: '123', description: '5', avgTimeTaken: 0, images: [], isEnabled: true, inventory: [], equipment: [], _id: '617f9efdf0347931684888fd' }, { typeOfPackage: 'sub', parents: '/Test123/', itemName: 'Regular', pricePerItem: 0, quantity: 0, quantityType: '1', description: '1', avgTimeTaken: 1, images: [], isEnabled: true, inventory: [], equipment: [], _id: '617f9efdf0347931684888fe' }, { typeOfPackage: 'subSub', parents: '/Test123/Reg3/', itemName: '500ML', pricePerItem: 123, quantity: 0, quantityType: '12', description: '123', avgTimeTaken: 51, images: [], isEnabled: true, inventory: [], equipment: [], _id: '617f9efdf0347931684888ff' }],
result = data
.reduce((r, o) => {
o
.parents
.split('/')
.filter(Boolean)
.reduce((t, itemName, i) => {
if (!t[itemName]) {
t[itemName] = { _: [] };
t._.push({ itemName, [getSub(i)]: t[itemName]._ });
}
return t[itemName];
}, r)
._
.push(o);
return r;
}, { _: [] })
._;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have the following code, which basically assigns a RoleManager object to the variable roles
var roles = receivedMessage.guild.roles;
console.log(roles['cache']);
Now, the log returns some mess that (partially) looks like this:
Collection [Map] {
'529502688183058443' => Role {
guild: Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '529502688183058443',
shardID: 0,
name: 'GuyDyamond Studios',
icon: '36e1f32f9fc98818872ca4583d50cc52',
splash: null,
discoverySplash: null,
region: 'us-east',
memberCount: 6,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '529502688183058445',
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'MEDIUM',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1600020773558,
defaultMessageNotifications: 'ALL',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 250000,
vanityURLCode: null,
vanityURLUses: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
preferredLocale: 'en-US',
ownerID: '423162345108275213',
emojis: [GuildEmojiManager]
},
id: '529502688183058443',
name: '#everyone',
color: 0,
hoist: false,
rawPosition: 0,
permissions: Permissions { bitfield: 104324673 },
managed: false,
mentionable: false,
deleted: false
},
'529672467200081922' => Role {
guild: Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '529502688183058443',
shardID: 0,
name: 'GuyDyamond Studios',
icon: '36e1f32f9fc98818872ca4583d50cc52',
splash: null,
discoverySplash: null,
region: 'us-east',
memberCount: 6,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '529502688183058445',
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'MEDIUM',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1600020773558,
defaultMessageNotifications: 'ALL',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 250000,
vanityURLCode: null,
vanityURLUses: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
preferredLocale: 'en-US',
ownerID: '423162345108275213',
emojis: [GuildEmojiManager]
},
Now, I've literally tried everything, but I can't seem to iterate over the object roles. I've tried a forEach function, a for...in... loop, etc etc, nothing. Additionally, I'm trying to get the name of each role and put it in an array, but I can't seem to get the name parameter. Any help on how to do this?
If all you need is the names, you can use Array.prototype.map:
console.log(
recievedMessage.guild.roles.cache.map((role) => role.name)
);
Example result:
['Admin', 'Mod', 'VIP', 'Member', 'Muted', '#everyone']
To iterate a function through every role, use:
recievedMessage.guild.roles.cache.forEach((role) => {
console.log(role.id);
});
So i have this following object in Javascript, and I am interested in only id: '410467873518256138', name: 'element1'
How can i extract this information from the object?
I tried storing it in object and doing object.id or object.name but it prints nothing.
'410467873518256138' => Emoji {
guild:
Guild {
members: [Object],
channels: [Object],
roles: [Object],
presences: [Object],
available: true,
id: '410467289767346186',
name: 'emoji_set4',
icon: null,
splash: null,
region: 'singapore',
memberCount: 2,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '410467289767346188',
embedEnabled: undefined,
verificationLevel: 0,
explicitContentFilter: 0,
joinedTimestamp: 1517933748730,
ownerID: '352458321456005123',
_rawVoiceStates: Collection {},
emojis: [Object] },
id: '410467873518256138',
name: 'element1',
requiresColons: true,
managed: false,
animated: false,
_roles: [] },
Also kindly explain what this syntax is '410467873518256138' => Emoji {, cause generally we write variable = {} to define an object.
So this is my method for getting all posts related to their corresponding topics.
const moment = require('moment');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const Post = require('../models/Post');
let posts = {
getPosts: function(req, res) {
return Post.find({ topicId: req.params._id })
.then(function(result) {
console.log('------------------------------------');
console.log('Headed to the Client: ', result);
console.log('------------------------------------');
res.json(result);
})
.catch(function(error) {
console.log('Nope! Nerd!');
return Promise.reject(error);
})
}
}
the result comes out like so:
[ { _id: 58deac2223b5b92ce45bdfac,
topicId: '58dd6f541919c541dbf9632d',
parentId: null,
content: '1 Post',
author: 'Bob',
createdAt: 2017-03-31T19:21:06.698Z,
isAnon: false,
__v: 0,
comments: [],
isArchieved: false,
isParent: true },
{ _id: 58deac2c23b5b92ce45bdfad,
topicId: '58dd6f541919c541dbf9632d',
parentId: null,
content: '2 Post',
author: 'Bob',
createdAt: 2017-03-31T19:21:16.622Z,
isAnon: false,
__v: 0,
comments: [],
isArchieved: false,
isParent: true },
{ _id: 58deac3c23b5b92ce45bdfae,
topicId: '58dd6f541919c541dbf9632d',
parentId: null,
content: '3 Post',
author: 'Bob',
createdAt: 2017-03-31T19:21:32.682Z,
isAnon: false,
__v: 0,
comments: [],
isArchieved: false,
isParent: true },
{ _id: 58deac5e23b5b92ce45bdfaf,
topicId: '58dd6f541919c541dbf9632d',
parentId: '58deac3c23b5b92ce45bdfae',
content: '1 Comment',
author: 'Kat',
createdAt: 2017-03-31T19:22:06.974Z,
isAnon: false,
__v: 0,
comments: [],
isArchieved: false,
isParent: false },
{ _id: 58deac6c23b5b92ce45bdfb0,
topicId: '58dd6f541919c541dbf9632d',
parentId: '58deac2223b5b92ce45bdfac',
content: '2 Comment',
author: 'Dave',
createdAt: 2017-03-31T19:22:20.071Z,
isAnon: false,
__v: 0,
comments: [],
isArchieved: false,
isParent: false },
{ _id: 58deac7a23b5b92ce45bdfb1,
topicId: '58dd6f541919c541dbf9632d',
parentId: '58deac2c23b5b92ce45bdfad',
content: '4 Comment',
author: 'Bob',
createdAt: 2017-03-31T19:22:34.865Z,
isAnon: false,
__v: 0,
comments: [],
isArchieved: false,
isParent: false } ]
I am getting stuck because I need to modify this list after it comes out of the database to grab the posts with parentIds and push them into their corresponding parents'comments array.
so the the result actually sent to the client looks like this:
[{
_id: 58deac2223b5b92ce45bdfa',
topicId: '58dd6f541919c541dbf9632d',
parentId: null,
content: '1 Post',
author: 'Bob',
isAnon: false,
__v: 0,
comments: [{
_id: 58deac6c23b5b92ce45bdfb0,
topicId: '58dd6f541919c541dbf9632d',
parentId: '58deac2223b5b92ce45bdfac',
content: '2 Comment',
author: 'Dave',
isAnon: false,
__v: 0,
comments: [],
isArchieved: false,
isParent: false
}],
isArchieved: false,
isParent: true
},
{
_id: 58deac2c23b5b92ce45bdfad,
topicId: '58dd6f541919c541dbf9632d',
parentId: null,
content: '2 Post',
author: 'Bob',
isAnon: false,
__v: 0,
comments: [{
_id: 58deac7a23b5b92ce45bdfb1,
topicId: '58dd6f541919c541dbf9632d',
parentId: '58deac2c23b5b92ce45bdfad',
content: '4 Comment',
author: 'Bob',
isAnon: false,
__v: 0,
comments: [],
isArchieved: false,
isParent: false
}],
isArchieved: false,
isParent: true
},
{
_id: 58deac3c23b5b92ce45bdfae,
topicId: '58dd6f541919c541dbf9632d',
parentId: null,
content: '3 Post',
author: 'Bob',
isAnon: false,
__v: 0,
comments: [{
_id: 58deac5e23b5b92ce45bdfaf,
topicId: '58dd6f541919c541dbf9632d',
parentId: '58deac3c23b5b92ce45bdfae',
content: '1 Comment',
author: 'Kat',
isAnon: false,
__v: 0,
comments: [],
isArchieved: false,
isParent: false
}],
isArchieved: false,
isParent: true
}
]
I know I need to recurse through the array but I'm stumped on the logic in between. Any help would be appreciated. Thank you so much.
You could use an object for collecting all nodes and append found children to the comments property. Get the nodes with parentId === null as root noded.
This approach works for unsorted data for any depth and use a single loop to get the nested result.
var data = [{ _id: '58deac2223b5b92ce45bdfac', topicId: '58dd6f541919c541dbf9632d', parentId: null, content: '1 Post', author: 'Bob', createdAt: '2017-03-31T19:21:06.698Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: true }, { _id: '58deac2c23b5b92ce45bdfad', topicId: '58dd6f541919c541dbf9632d', parentId: null, content: '2 Post', author: 'Bob', createdAt: '2017-03-31T19:21:16.622Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: true }, { _id: '58deac3c23b5b92ce45bdfae', topicId: '58dd6f541919c541dbf9632d', parentId: null, content: '3 Post', author: 'Bob', createdAt: '2017-03-31T19:21:32.682Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: true }, { _id: '58deac5e23b5b92ce45bdfaf', topicId: '58dd6f541919c541dbf9632d', parentId: '58deac3c23b5b92ce45bdfae', content: '1 Comment', author: 'Kat', createdAt: '2017-03-31T19:22:06.974Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: false }, { _id: '58deac6c23b5b92ce45bdfb0', topicId: '58dd6f541919c541dbf9632d', parentId: '58deac2223b5b92ce45bdfac', content: '2 Comment', author: 'Dave', createdAt: '2017-03-31T19:22:20.071Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: false }, { _id: '58deac7a23b5b92ce45bdfb1', topicId: '58dd6f541919c541dbf9632d', parentId: '58deac2c23b5b92ce45bdfad', content: '4 Comment', author: 'Bob', createdAt: '2017-03-31T19:22:34.865Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: false }],
tree = function (data, root) {
var r = [],
o = {};
data.forEach(function (a) {
a.comments = (o[a._id] && o[a._id].comments || []).concat();
o[a._id] = a;
if (a.parentId === root) {
r.push(a);
} else {
o[a.parentId] = o[a.parentId] || {};
o[a.parentId].comments = o[a.parentId].comments || [];
o[a.parentId].comments.push(a);
}
});
return r;
}(data, null);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I need to automate some API tests with frisby.js, and I'm stuck at accessing to some data which is nested inside JSON response body.
Below is my code
var frisby = require('c:/frisby');
frisby.create('Request available Voyages')
.post('someURL', {
departureVoyage: {
from: "500",
to: "500",
date: '2017-01-07'}})
.inspectJSON()
.afterJSON(function (voyage) {
console.log(voyage.departureVoyage.voyages);}
Below is the output of inspectJSON() function
{ type: 'voyageResponseWsDTO',
departureVoyage:
{ date: '2017-01-07',
voyages:
[ { endTime: '22:30',
quotas:
[ { id: '8796095719239',
limit: 66,
name: 'PROMOTION',
price: '34',
priceCurrency: 'USD' },
{ id: '8796095620935',
limit: 271,
name: 'ECONOMY',
price: '51',
priceCurrency: 'USD' },
{ id: '8796095489863',
limit: 19,
name: 'BUSINESS',
price: '72',
priceCurrency: 'USD' },
{ id: '8796234721095',
limit: 0,
name: 'CAR PROMOTION',
price: '84',
priceCurrency: 'USD' },
{ id: '8796095752007',
limit: 2,
name: 'VIP',
price: '800',
priceCurrency: 'USD' } ],
time: '20:00',
vessel:
{ carriesVehicles: true,
TypeCode: 'FE',
TypeName: 'Ferry' } } ] } }
and below is the output of console.log(voyage.departureVoyage.voyages);
[ { endTime: '22:30',
quotas: [ [Object], [Object], [Object], [Object], [Object] ],
time: '20:00',
vessel:
{ carriesVehicles: true,
TypeCode: 'FE',
TypeName: 'Ferry' } } ]
My problem is, when I try to access content of "quotas" with "console.log(voyage.departureVoyage.voyages.quotas);" I get "undefined" message.
Do you know a way how can I reach data of this "quotas"? Because I need to reach properties of this "quotas", like id of one them.
Thanks
voyage.departureVoyage.voyages is an array, and quotas is in the first item of that array,
So refer it like below for quotas inside it,
voyage.departureVoyage.voyages[0].quotas