I am currently developing an endpoint where I want to return one object from 4 different tables. I get the record of each table in JSON format from sequelize. I have a location, service, staff, and Tenant. How can I merge them into one object but nested.
For example:
The data I get from sequelize for staff:
{
"id": 2,
"profession": "Dentist",
"note": "Good Man",
"holidays": "Saturday",
"specialDays": null,
"createdAt": "2023-01-27T14:23:52.000Z",
"updatedAt": "2023-01-27T14:23:52.000Z",
}
All other data are in a similar format. But I want to merge them to return something like:
{ staff:{
"id": 2,
"profession": "Dentist",
"note": "Good Man",
"holidays": "Saturday",
"specialDays": null,
"createdAt": "2023-01-27T14:23:52.000Z",
"updatedAt": "2023-01-27T14:23:52.000Z",},
location:{
"id": 1,
"name": "Branch 1",
"address": "37 Automatic Handling",
"description": "This is our main branch",
"latitude": "564233",
"longtitude": "4441256",
"visible": true,
"createdAt": "2023-01-27T14:05:37.000Z",
"updatedAt": "2023-01-27T14:05:37.000Z",
}
}
Just make an object yourself
// (inside of an async function)
const location = await // sequelize code to get this info
const service = await // sequelize code to get this info
const staff = await // sequelize code to get this info
const tenant = await // sequelize code to get this info
return res.json({
location,
service,
staff,
Tenant: tenant, // remove "Tenant: " if the capital was a typo or you don't care
});
This should work
const staff = {
"id": 2,
"profession": "Dentist",
"note": "Good Man",
"holidays": "Saturday",
"specialDays": null,
"createdAt": "2023-01-27T14:23:52.000Z",
"updatedAt": "2023-01-27T14:23:52.000Z",
};
const location1 = {
"id": 1,
"name": "Branch 1",
"address": "37 Automatic Handling",
"description": "This is our main branch",
"latitude": "564233",
"longtitude": "4441256",
"visible": true,
"createdAt": "2023-01-27T14:05:37.000Z",
"updatedAt": "2023-01-27T14:05:37.000Z",
};
const mergedObject = { staff, location1 };
console.log(mergedObject);
Related
I have this complicated data in MongoDB, I want to reconstruct it into something like the second JSON, I tried both MongoDB aggregate and javascript spread, but I couldn't figure it out.
Original Data
[
{
"_id": "61ff24b2db73094dd3029c7e",
"TeamName": "GoodTeam",
"TeamImage": "Avatar",
"TeamMember": [
{
"name": "Aimee",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test2#gmail.com",
"timezone": "PST",
"_id": "61ff25fcd2a0b9e13ee8989c"
},
{
"name": "Kai",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "school021195#gmail.com",
"timezone": "PST",
"_id": "61ff3114d3d343bd673f5ad3"
},
{
"name": "Iren",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test1#gmail.com",
"timezone": "AKST",
"_id": "61ff3114d3d343bd673f5ad4"
}
],
"createdAt": "2022-02-06T01:30:26.893Z",
"updatedAt": "2022-02-06T02:23:16.660Z",
"__v": 0
}
]
Reconstruct Data
[
{
"timezone":"PST",
"TeamMember":[
{
"name": "Aimee",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test2#gmail.com",
"timezone": "PST",
"_id": "61ff25fcd2a0b9e13ee8989c"
},
{
"name": "Kai",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "school021195#gmail.com",
"timezone": "PST",
"_id": "61ff3114d3d343bd673f5ad3"
},
{
"timezone":"AKST",
"TeamMember":[
{
"name": "Iren",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test1#gmail.com",
"timezone": "AKST",
"_id": "61ff3114d3d343bd673f5ad4"
}
]
}
]
And how should I deal with this kind of data reconstruction in the front-end or back-end? Which one is better practice?
You can always create a custom transformer for converting one JSON to another JSON and I would suggest you to let the back-end handle this responsibility.
Below is one example using Javascript.
const firstJson = `[
{
"_id": "61ff24b2db73094dd3029c7e",
"TeamName": "GoodTeam",
"TeamImage": "Avatar",
"TeamMember": [
{
"name": "Aimee",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test2#gmail.com",
"timezone": "PST",
"_id": "61ff25fcd2a0b9e13ee8989c"
},
{
"name": "Kai",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "school021195#gmail.com",
"timezone": "PST",
"_id": "61ff3114d3d343bd673f5ad3"
},
{
"name": "Iren",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test1#gmail.com",
"timezone": "AKST",
"_id": "61ff3114d3d343bd673f5ad4"
}
],
"createdAt": "2022-02-06T01:30:26.893Z",
"updatedAt": "2022-02-06T02:23:16.660Z",
"__v": 0
}
]`;
const firstJsonObj = JSON.parse(firstJson);
const map = new Map();
for(let i =0;i<firstJsonObj.length;i++){
for(let j =0;j<firstJsonObj[i].TeamMember.length;j++){
let timezone = firstJsonObj[i].TeamMember[j].timezone;
if(map.has(timezone)){
const team = map.get(timezone);
team.push(firstJsonObj[i].TeamMember[j]);
map.set(timezone,team);
}
else{
map.set(timezone,[firstJsonObj[i].TeamMember[j]])
}
}
}
const secondJson = Array.from(map,function(element){
const [key,value] = element;
return {
timezone : key,
TeamMember : value
}
});
console.log(JSON.stringify(secondJson));
EDIT:
If you want query data from mongodb itself you can use below query to get the output
db.collection.aggregate([
{
"$unwind": "$TeamMember"
},
{
"$group": {
"_id": {
"timezone": "$TeamMember.timezone"
},
"TeamMember": {
"$push": "$$ROOT.TeamMember"
}
}
},
{
"$project": {
"_id": 0,
"timezone": "$_id.timezone",
"TeamMember": 1
}
}
])
It is better to do it in the backend and recommended.
You can achieve this by multiple ways in the backend using mongo aggregation framework. It is very powerful framework with multiple operators to handle these kind of data.
I’m developing an app with Vue.js that’s using Vuetify for some nice material design components. My data is stored in Firebase Cloud Firestore. I want to create a Vuetify table that is optimized for the following usage.
Functionality
The table is used to check availability for multiple event dates. Users are listed on the left side and are grouped by their position in the company (e.g. consultant, manager etc.). These groups should be visible but can be hidden by tapping on the arrow. It should also be possible to hide position groups completely. The event availability status is shown in three colors (green, red or blue). Later I want to add buttons or icons to the cells for more features. If the user taps on their cell a dialog should open to change the availability. If you tap on the event in the header a dialog should open that shows more event details.
The table should look like this mockup:
The table is scrollable up/down to see all users, left/right to check future events. However the event header and the user bar on the right should be fixed.
Data in Firebase Cloud Firestore:
events
—> [event_id] // every event has an unique id
title: String
startdate: Date
enddate: Date
—> [availability] // every [event] contains the availability of users
—> [user_id]
status: String // attendance, no attendance, not sure
comment: String // details that users adds to their response
What's the best way to start developing the table?
Here is some dummy data in JSON format to get a feeling of what to work with:
{
"events": {
"event1": {
"id": "event1",
"title": "Lunch with Santa Claus",
"startdate": "03/11/2020 13:00",
"enddate": "03/11/2020 14:00",
"availability": {
"user100": {
"userID": "user100",
"status": "not sure"
},
"user103": {
"userID": "user103",
"status": "attendance",
"comment": "Looking forward to lunch with Santa"
},
"user108": {
"userID": "user108",
"status": "attendance"
}
}
},
"event2": {
"id": "event2",
"title": "Meeting with Robin Hood",
"startdate": "08/11/2020 10:00",
"enddate": "08/11/2020 12:00",
"availability": {
"user100": {
"userID": "user100",
"status": "attendance",
"comment": "Will be late"
},
"user101": {
"userID": "user101",
"status": "no attendance"
},
"user102": {
"userID": "user102",
"status": "not sure"
},
"user103": {
"userID": "user103",
"status": "attendance",
"comment": "Robin Hood is great!"
},
"user108": {
"userID": "user108",
"status": "attendance"
}
}
},
"event3": {
"id": "event3",
"title": "Team Meeting",
"startdate": "10/11/2020 09:00",
"enddate": "10/11/2020 10:00",
"availability": {
"user108": {
"userID": "user108",
"status": "no attendance"
},
"user105": {
"userID": "user105",
"status": "not sure"
},
"user102": {
"userID": "user102",
"status": "not sure"
},
"user103": {
"userID": "user103",
"status": "attendance",
"comment": "Looking forward to lunch with Santa"
},
"user109": {
"userID": "user109",
"status": "attendance"
}
}
}
},
"users": {
"user100": {
"id": "user100",
"name": "John Doe",
"position": "Manager"
},
"user101": {
"id": "user101",
"name": "Anna Black",
"position": "Consultant"
},
"user102": {
"id": "user102",
"name": "Tom Green",
"position": "Associate"
},
"user103": {
"id": "user103",
"name": "Matt White",
"position": "Senior Consultant"
},
"user104": {
"id": "user104",
"name": "Peter Blue",
"position": "Manager"
},
"user105": {
"id": "user105",
"name": "Ted Yellow",
"position": "Associate"
},
"user106": {
"id": "user106",
"name": "Lewis Elefant",
"position": "Associate"
},
"user107": {
"id": "user107",
"name": "Matt Shark",
"position": "Senior Consultant"
},
"user108": {
"id": "user108",
"name": "Donald Duck",
"position": "Associate"
},
"user109": {
"id": "user109",
"name": "Lisa Bird",
"position": "Manager"
},
"user110": {
"id": "user110",
"name": "Bailey Wolf",
"position": "Manager"
}
}
}
Any help is very much appreciated, thanks!
I have a collection of adverts, inside that there is a array of objects of bids made by other users to that specific advert.
The thing I want to return is only the bids made by the current user so it has to match with req.user.id (where i hold the jwt token)
So I tried filter method but it returned an empty array, then tried with for in loop, got another empty set of square brackets...
Here is my 'adverts' collection;
For example, from the collection below, i want to get an array of objects only contains bids made by this user (user : 5f7c40a0ec1a374c6c924610).
[
{
"_id": "5f7d924371469c21f866fa16",
"user": "5f7c40a0ec1a374c6c924610",
"title": "Logistics for carrying chemicals",
"text": "We need a approximately 20 trucks of logistics line for carrying our chemicals",
"status": false,
"company": "Bayrak Company",
"location": "San Francisco",
"date": "2020-10-07T10:02:43.811Z",
"bids": [
{
"_id": "5f7dc3225a835c359432ab15",
"user": "5f7c40a0ec1a374c6c924610",
"bid": "50000",
"company": "Bayrak Company",
"avatar": "https://gravatar.com/avatar/4ecfd3d216693adc6867bf09c9087b1a?d=mm&r=pg&s=200",
"date": "2020-10-07T13:31:14.890Z"
},
{
"_id": "5f7db5fea762d34054072f8c",
"user": "5f7c40a0ec1a374c6c924610",
"bid": "50000",
"company": "Bayrak Company",
"avatar": "https://gravatar.com/avatar/4ecfd3d216693adc6867bf09c9087b1a?d=mm&r=pg&s=200",
"date": "2020-10-07T12:35:10.237Z"
}
],
"comments": [],
"__v": 2
},
{
"_id": "5f7db0153870fd4178390a4d",
"user": "5f7c40a0ec1a374c6c924610",
"title": "Need construction trucks for new buildings",
"text": "The new constrution area needs approximately 15 trucks",
"status": false,
"company": "Bayrak Company",
"location": "San Francisco",
"date": "2020-10-07T12:09:57.362Z",
"bids": [],
"comments": [],
"__v": 0
}
]
**And here is what I tried so far; **
// #route GET /api/adverts/mybids
// #desc Get bids that I made
// #access Private.
router.get('/mybids', auth, async (req, res) => {
try {
let adverts = await Advert.find();
let mybids = [];
let bidsByMe = [];
for (let x in adverts) {
let bid = adverts[x].bids;
for (let y in bid) {
let innerBid = bid[y];
mybids.push(innerBid);
}
}
for (let x in mybids) {
let bid = mybids[x];
if (bid.user == req.user.id) {
bidsByMe.push(bid);
}
}
res.json(bidsByMe);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error...');
}
});
You can run this query :
db.collection.aggregate([
{
$match: {
user: "5f7c40a0ec1a374c6c924610",
"bids.user": "5f7c40a0ec1a374c6c924610"
}
},
{
$group: {
_id: "$_id",
user: {$first: "$user"},
title: {$first: "$title"},
text: {$first: "$text"},
status: {$first: "$status"},
location: {$first: "$location"},
bids:{$first:"$bids"}
}
}
])
//check below URL
https://mongoplayground.net/p/TBGPDXO5lIl
I am not sure how to form this question, but I will do my best.
I don't know how to remove object by _id from 'list:' part.
So, I have one array, and inside of that array I have list of objects,inside of these objects I have again array with objects, so I want to remove one object from that last array, how I can do that?
Cannot fix it for 2 days, I'm stucked!
Thanks!
[
{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [
{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [
{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
]
Using Vanilla JS:
function findAndRemove(data, id) {
data.forEach(function(obj) { // Loop through each object in outer array
obj.list = obj.list.filter(function(o) { // Filter out the object with unwanted id, in inner array
return o._id != id;
});
});
}
var data = [{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
];
// Empty almost all of list, except middle one
findAndRemove(data, "599a1322bf50847b0972a384");
findAndRemove(data, "599a1322bf50847b0972a386");
findAndRemove(data, "599a12fdbf50847b0972a2a5");
findAndRemove(data, "599a12fdbf50847b0972a2a6");
findAndRemove(data, "599a12fdbf50847b0972a2ab");
console.log(data);
Cleared everything except middle list, just for better visualization.
#Abhijit Kar your one is working perfectly, thanks mate!
How I can later splice this list?
When I was working with objects from first array, I did it like this :
var inventory = jsonArrayList;
for (var i = 0; i < inventory.length; i++) {
if (inventory[i]._id == deleteProductById) {
vm.items.splice(i, 1);
break;
}
}
It would be very helpful, thanks alot!
You can use Array.map and Array.filter to accomplish this. Detailed explanation in comments:
PS: This snippet uses ES6 arrow functions and spread operator
function removeById(arr, id) {
// Array.map iterates over each item in the array,
// and executes the given function on the item.
// It returns an array of all the items returned by the function.
return arr.map(obj => {
// Return the same object, if the list is empty / null / undefined
if (!obj.list || !obj.list.length) return obj;
// Get a new list, skipping the item with the spedified id
const newList = obj.list.filter(val => val._id !== id);
// map function returns the new object with the filtered list
return { ...obj, list: newList };
});
}
const oldArray = <YOUR_ORIGINAL_ARRAY>;
const newArray = removeById(arr, "599a12fdbf50847b0972a2a5");
I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }