Cannot get events in Javascript FullCalendar with Laravel - javascript

I have a page in the system that I am developing that needs to have a FullCalendar. The user will view, add, update tasks or events in that calendar.
I don't know what's happening, I can't get to display the events stored in my database.
I'm using Sqlite database running in Laravel 6.3.0
See below for reference code.
Fullcalendar generation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var calendar = $('#calendar').fullCalendar({
editable: true,
events: "{{url('/home')}}",
displayEventTime: true,
editable: true,
eventRender: function (start, end,event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
select: function (start, end, allDay) {
var start_date = moment(start, 'DD.MM.YYYY').format('YYYY-MM-DD');
var end_date = moment(end, 'DD.MM.YYYY').format('YYYY-MM-DD');
$('#createTask').modal('show');
$('#saveTaskBtn').click(function () {
title = $('#taskTitle').val();
description = $('#taskDescription').val();
var post_data = "name="+title+"&description="+description+"&start_date="+start_date+"&end_date="+end_date;
// var post_data = {
// name:title,
// description: description,
// start_date: start_date,
// end_date: end_date
// };
$.ajax({
url: "{{url('home/create')}}",
data: post_data,
type: "POST",
success: function (data) {
displayMessage("Added Successfully");
},
error : function (data) {
console.log(data);
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start_date,
end: end_date,
allDay: allDay
},
true
);
calendar.fullCalendar('unselect');
});
}
});
ROUTE
Route::get('/home','TasksController#index')->name('home');
Route::post('home/create','TasksController#create');
Route::post('home/update','TasksController#update');
Route::post('home/delete','TasksController#destroy');
TasksController - $data has values passed in the view
public function index()
{
if (request()->ajax()) {
$start = (!empty($_GET["start_date"])) ? ($_GET["start_date"]) : ('');
$end = (!empty($_GET["end_date"])) ? ($_GET["end_date"]) : ('');
// $data = Task::whereDate('start_date', '>=', $start)->whereDate('end_date', '<=', $end)->get(['id', 'title', 'description', 'start_date', 'end_date']);
$data = Task::all();
dd(Response::json($data));
return Response::json($data);
}
return view('home');
}
$data JSON Response
JsonResponse {#279
#data: "[{"id":1,"name":"TEST","description":"TEST","start_date":"2019-11-02","end_date":"2019-11-03","created_at":null,"updated_at":null},{"id":2,"name":"TEST","description":"TEST","start_date":"2019-12-07","end_date":"2019-12-08","created_at":null,"updated_at":null},{"id":3,"name":"TEST","description":"TEST","start_date":"2019-11-02","end_date":"2019-11-03","created_at":null,"updated_at":null},{"id":4,"name":"TEST","description":"TEST","start_date":"2019-11-08 00:00:00","end_date":"2019-11-09 00:00:00","created_at":null,"updated_at":null}]"
#callback: null
#encodingOptions: 0
+headers: ResponseHeaderBag {#290
#computedCacheControl: array:2 [
"no-cache" => true
"private" => true
]
#cookies: []
#headerNames: array:3 [
"cache-control" => "Cache-Control"
"date" => "Date"
"content-type" => "Content-Type"
]
#headers: array:3 [
"cache-control" => array:1 [
0 => "no-cache, private"
]
"date" => array:1 [
0 => "Mon, 25 Nov 2019 11:50:48 GMT"
]
"content-type" => array:1 [
0 => "application/json"
]
]
#cacheControl: []
}
#content: "[{"id":1,"name":"TEST","description":"TEST","start_date":"2019-11-02","end_date":"2019-11-03","created_at":null,"updated_at":null},{"id":2,"name":"TEST","description":"TEST","start_date":"2019-12-07","end_date":"2019-12-08","created_at":null,"updated_at":null},{"id":3,"name":"TEST","description":"TEST","start_date":"2019-11-02","end_date":"2019-11-03","created_at":null,"updated_at":null},{"id":4,"name":"TEST","description":"TEST","start_date":"2019-11-08 00:00:00","end_date":"2019-11-09 00:00:00","created_at":null,"updated_at":null}]"
#version: "1.0"
#statusCode: 200
#statusText: "OK"
#charset: null
+original: Collection {#292
#items: array:4 [
0 => Task {#293
#fillable: array:4 [
0 => "name"
1 => "description"
2 => "start_date"
3 => "end_date"
]
#table: "tasks"
#connection: "sqlite"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [
"id" => "1"
"name" => "TEST"
"description" => "TEST"
"start_date" => "2019-11-02"
"end_date" => "2019-11-03"
"created_at" => null
"updated_at" => null
]
#original: array:7 [
"id" => "1"
"name" => "TEST"
"description" => "TEST"
"start_date" => "2019-11-02"
"end_date" => "2019-11-03"
"created_at" => null
"updated_at" => null
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
}
1 => Task {#294
#fillable: array:4 [
0 => "name"
1 => "description"
2 => "start_date"
3 => "end_date"
]
#table: "tasks"
#connection: "sqlite"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [
"id" => "2"
"name" => "TEST"
"description" => "TEST"
"start_date" => "2019-12-07"
"end_date" => "2019-12-08"
"created_at" => null
"updated_at" => null
]
#original: array:7 [
"id" => "2"
"name" => "TEST"
"description" => "TEST"
"start_date" => "2019-12-07"
"end_date" => "2019-12-08"
"created_at" => null
"updated_at" => null
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
}
2 => Task {#295
#fillable: array:4 [
0 => "name"
1 => "description"
2 => "start_date"
3 => "end_date"
]
#table: "tasks"
#connection: "sqlite"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [
"id" => "3"
"name" => "TEST"
"description" => "TEST"
"start_date" => "2019-11-02"
"end_date" => "2019-11-03"
"created_at" => null
"updated_at" => null
]
#original: array:7 [
"id" => "3"
"name" => "TEST"
"description" => "TEST"
"start_date" => "2019-11-02"
"end_date" => "2019-11-03"
"created_at" => null
"updated_at" => null
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
}
3 => Task {#296
#fillable: array:4 [
0 => "name"
1 => "description"
2 => "start_date"
3 => "end_date"
]
#table: "tasks"
#connection: "sqlite"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [
"id" => "4"
"name" => "TEST"
"description" => "TEST"
"start_date" => "2019-11-08 00:00:00"
"end_date" => "2019-11-09 00:00:00"
"created_at" => null
"updated_at" => null
]
#original: array:7 [
"id" => "4"
"name" => "TEST"
"description" => "TEST"
"start_date" => "2019-11-08 00:00:00"
"end_date" => "2019-11-09 00:00:00"
"created_at" => null
"updated_at" => null
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
}
]
}
+exception: null
}

Related

How to change the keys in nested array of objects

Following is my array, and I need to replace the keys name with title and Email with subtitle.
I tried some ways, but I still need to fulfill my requirement. Please provide any solution to this.
const newUpdatedList = [];
resArr.forEach((res) => {
const obj = {
title: res.name,
subtitle: res.attributes.Email
};
if (res.children) {
const newList = res.children.map((ch) => {
return {
title: ch.name,
subtitle: ch.attributes.Email,
};
});
obj.children = newList;
}
newUpdatedList.push(obj);
});
const resArr =
[ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2'
, name : 'Harsha ABC'
, custom_id : 'mani78989-1gfqv04bo'
, attributes : { Email: 'harsha#gmail.com', Role: 'admin'}
, children:
[ { user_id : 'd748037a-b445-41c2-b82f-4d6ee9396714'
, name : 'Lavaraju Allu'
, custom_id : 'mani78989-1gfqv472q'
, attributes : { Email: 'raju#gmail.com', Role: 'Manager'}
, children:
[ { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1'
, name : 'Ramesh Allu'
, custom_id : 'mani78989-1gh14i13t'
, attributes : { Email: 'ramesh#gmail.com', Role: 'Retailer'}
, children:
[ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2'
, name : 'Harsha ABC'
, custom_id : 'mani78989-1gh15nrev'
, attributes : { Email: 'harsha#gmail.com', Role: 'Delivery Manager'}
, children : []
} ] } ] }
, { user_id : '550cc296-d7e4-44fb-9d62-4c6755b3f6f2'
, name : 'Suresh Kunisetti'
, custom_id : 'mani78989-1gfqv6idi'
, attributes : { Email: 'suresh#gmail.com', Role: 'Super Admin'}
, children:
[ { user_id : '45cf19f8-36c1-4669-9333-1226c4f7b66b'
, name : 'Harish Three'
, custom_id : 'mani78989-1ggv5vffb'
, attributes : { Email: 'harish234#gmail.com', Role: 'Delivery Manager'}
, children : []
} ] }
, { user_id : '2c8535be-5fe7-40f0-892f-0f9bcffe0baa'
, name : 'Sandeep Bbb'
, custom_id : 'mani78989-1gh14m5p4'
, attributes : { Email: 'sandeep#gmail.com', Role: 'Delivery Manager'}
, children : []
}
, { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1'
, name : 'Ramesh Allu'
, custom_id : 'mani78989-1gh14pc6p'
, attributes : { Email: 'ramesh#gmail.com', Role: 'Manager'}
, children : [ ]
} ] }
]
Expected output is
const resArr =
[ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2'
, title : 'Harsha ABC'
, custom_id : 'mani78989-1gfqv04bo'
, attributes : { subtitle: 'harsha#gmail.com', Role: 'admin'}
, children:
[ { user_id : 'd748037a-b445-41c2-b82f-4d6ee9396714'
, title : 'Lavaraju Allu'
, custom_id : 'mani78989-1gfqv472q'
, attributes : { subtitle: 'raju#gmail.com', Role: 'Manager'}
, children:
[ { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1'
, title : 'Ramesh Allu'
, custom_id : 'mani78989-1gh14i13t'
, attributes : { subtitle: 'ramesh#gmail.com', Role: 'Retailer'}
, children:
[ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2'
, title : 'Harsha ABC'
, custom_id : 'mani78989-1gh15nrev'
, attributes : { subtitle: 'harsha#gmail.com', Role: 'Delivery Manager'}
, children : []
} ] } ] }
, { user_id : '550cc296-d7e4-44fb-9d62-4c6755b3f6f2'
, title : 'Suresh Kunisetti'
, custom_id : 'mani78989-1gfqv6idi'
, attributes : { subtitle: 'suresh#gmail.com', Role: 'Super Admin'}
, children:
[ { user_id : '45cf19f8-36c1-4669-9333-1226c4f7b66b'
, title : 'Harish Three'
, custom_id : 'mani78989-1ggv5vffb'
, attributes : { subtitle: 'harish234#gmail.com', Role: 'Delivery Manager'}
, children : []
} ] }
, { user_id : '2c8535be-5fe7-40f0-892f-0f9bcffe0baa'
, title : 'Sandeep Bbb'
, custom_id : 'mani78989-1gh14m5p4'
, attributes : { subtitle: 'sandeep#gmail.com', Role: 'Delivery Manager'}
, children : []
}
, { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1'
, title : 'Ramesh Allu'
, custom_id : 'mani78989-1gh14pc6p'
, attributes : { subtitle: 'ramesh#gmail.com', Role: 'Manager'}
, children : []
} ] }
]
You can use the recursive function that I created. This function is taking in an object that looks like sample_obj and then recreates the resArr where name is title and email is subtitle. Take a look:
function recursive_fix(obj) {
const sample_obj = {
user_id: obj.user_id,
title: obj.name,
custom_id: obj.custom_id,
attributes: {subtitle: obj.attributes.Email, Role: obj.attributes.Role},
children: []
};
// only adding recursive if the children array is not empty
if (obj.children.length !== 0) {
obj.children.forEach((childz) => {
sample_obj.children.push({children: [recursive_fix(childz)]})
})
}
return sample_obj
};
const newUpdatedList = [];
resArr.forEach((res) => {
newUpdatedList.push(recursive_fix(res))
})
Here's a recursive solution.
const resArr= [{"user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2","name": "Harsha ABC","custom_id": "mani78989-1gfqv04bo","attributes": {"Email": "harsha#gmail.com","Role": "admin"},"children": [{"user_id": "d748037a-b445-41c2-b82f-4d6ee9396714","name": "Lavaraju Allu","custom_id": "mani78989-1gfqv472q","attributes": {"Email": "raju#gmail.com","Role": "Manager"},"children": [{"user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1","name": "Ramesh Allu","custom_id": "mani78989-1gh14i13t","attributes": {"Email": "ramesh#gmail.com","Role": "Retailer"},"children": [{"user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2","name": "Harsha ABC","custom_id": "mani78989-1gh15nrev","attributes": {"Email": "harsha#gmail.com","Role": "Delivery Manager"},"children": []}]}]},{"user_id": "550cc296-d7e4-44fb-9d62-4c6755b3f6f2","name": "Suresh Kunisetti","custom_id": "mani78989-1gfqv6idi","attributes": {"Email": "suresh#gmail.com","Role": "Super Admin"},"children": [{"user_id": "45cf19f8-36c1-4669-9333-1226c4f7b66b","name": "Harish Three","custom_id": "mani78989-1ggv5vffb","attributes": {"Email": "harish234#gmail.com","Role": "Delivery Manager"},"children": []}]},{"user_id": "2c8535be-5fe7-40f0-892f-0f9bcffe0baa","name": "Sandeep Bbb","custom_id": "mani78989-1gh14m5p4","attributes": {"Email": "sandeep#gmail.com","Role": "Delivery Manager"},"children": []},{"user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1","name": "Ramesh Allu","custom_id": "mani78989-1gh14pc6p","attributes": {"Email": "ramesh#gmail.com","Role": "Manager"},"children": []}]}]
function changeTitles(Obj){
Obj.title = Obj.name;
Obj.attributes.subtitle = Obj.attributes.Email;
delete Obj.name;
delete Obj.attributes.Email;
if (Obj.children) {
Obj.children.forEach(changeTitles)
}
}
const clone = JSON.parse(JSON.stringify(resArr)) // Because the function mutates the object
clone.forEach(changeTitles)
console.log(clone)
I was a little late with my answer, so it looks like a copy of Brother58697's answer. The only difference is maybe the structuredClone() method, a newish global method:
const resArr= [ { "user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2", "name": "Harsha ABC", "custom_id": "mani78989-1gfqv04bo", "attributes": { "Email": "harsha#gmail.com", "Role": "admin" }, "children": [ { "user_id": "d748037a-b445-41c2-b82f-4d6ee9396714", "name": "Lavaraju Allu", "custom_id": "mani78989-1gfqv472q", "attributes": { "Email": "raju#gmail.com", "Role": "Manager" }, "children": [ { "user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1", "name": "Ramesh Allu", "custom_id": "mani78989-1gh14i13t", "attributes": { "Email": "ramesh#gmail.com", "Role": "Retailer" }, "children": [ { "user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2", "name": "Harsha ABC", "custom_id": "mani78989-1gh15nrev", "attributes": { "Email": "harsha#gmail.com", "Role": "Delivery Manager" }, "children": [] } ] } ] }, { "user_id": "550cc296-d7e4-44fb-9d62-4c6755b3f6f2", "name": "Suresh Kunisetti", "custom_id": "mani78989-1gfqv6idi", "attributes": { "Email": "suresh#gmail.com", "Role": "Super Admin" }, "children": [ { "user_id": "45cf19f8-36c1-4669-9333-1226c4f7b66b", "name": "Harish Three", "custom_id": "mani78989-1ggv5vffb", "attributes": { "Email": "harish234#gmail.com", "Role": "Delivery Manager" }, "children": [] } ] }, { "user_id": "2c8535be-5fe7-40f0-892f-0f9bcffe0baa", "name": "Sandeep Bbb", "custom_id": "mani78989-1gh14m5p4", "attributes": { "Email": "sandeep#gmail.com", "Role": "Delivery Manager" }, "children": [] }, { "user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1", "name": "Ramesh Allu", "custom_id": "mani78989-1gh14pc6p", "attributes": { "Email": "ramesh#gmail.com", "Role": "Manager" }, "children": [] } ] } ];
function trans(arr){
arr.forEach((o)=>{
o.title=o.name; delete(o.name);
o.attributes.subtitle=o.attributes.Email; delete(o.attributes.Email);
trans(o.children)
})
}
let result=structuredClone(resArr);
trans(result);
console.log(result);
I am not 100% sure I understand correctly what you're trying to do, but it seems you are trying to change the key names in an array of objects. Let me know if this is wrong. Something like this would work in that case"
const arrayOfObj = [{
name: 'value1',
email: 'value2'
}, {
name: 'value1',
email: 'value2'
}];
const newArrayOfObj = arrayOfObj.map(({
name: title,
email: subtitle,
...rest
}) => ({
title,
subtitle,
...rest
}));
console.log(newArrayOfObj);
found this answer here
A quick solution could be to stringify, string replace and parse back to object/array.
Something like this:
const asString = JSON.stringify(resArr);
const replacedNames = asString.replace(/name/g, "title");
const replacedEmail = replacedNames.replace(/Email/g, "subtitle");
const result = JSON.parse(replacedEmail);
the changed object/array is in result.
One of the Simplest way we can use is to use Object.assign something like this:
a={'name': 'xyz', 'Email': 'xyz#gmail.com'};
b= Object.assign({'title': a.name, 'subtitle': a.Email});

how to avoid duplicate key error collection in mongodb

i want to build a cart for my website, this is the schema for the cart:
const productSchema = require("./product")[1];
const cartItemSchema = new Schema<CartItem>(
{
product: productSchema,
quantity: {
type: Number,
required: true,
min: [1, "Quantity can not be less then 1."],
},
},
{
timestamps: true,
}
);
const CartSchema = new Schema(
{
userID: {
type: Schema.Types.ObjectId,
ref: "User",
},
items: [cartItemSchema],
},
{ timestamps: true }
);
module.exports = model<Cart>("Cart", CartSchema);
the problem is, when I add a product in a specific user cart, while the same product is allready added to another user cart document, I get this error:
"message":"cannot add to cart E11000 duplicate key error collection: elec-store.carts index: items.productID_1 dup key: { items.productID: null }, stack: MongoError: E11000 duplicate key error collection: elec-store.carts index: items.productID_1 dup key
this is the add function
public async add(cartItem: CartItem, userID: string): Promise<Cart> {
let cartInDB = null;
await CartModel.findOne({ userID: userID }, (err, cart) => {
cartInDB = cart;
});
if (AppUtils.hasValue(cartInDB)) {
const index = cartInDB.items.findIndex(
(item) => item.product._id.toString() === cartItem.product._id
);
if (index !== -1) {
cartInDB.items[index].quantity =
cartInDB.items[index].quantity + cartItem.quantity;
cartInDB.items[index].product._id = cartItem.product._id;
const cartAfterAdding = await cartInDB.save();
return cartAfterAdding;
} else {
await CartModel.update(
{ _id: cartInDB._id },
{ $push: { items: cartItem } }
);
}
return cartInDB;
} else {
const itemsArray: CartItem[] = [];
itemsArray.push(cartItem);
let createdCart = new CartModel({
userID: userID,
items: itemsArray,
});
await createdCart.save(); \\ this is where the problem occurs
return createdCart;
}
}
and this is how my cart looks like in mongodb document:
db.carts.find().pretty()
{
"_id" : ObjectId("60ea9fb81b2b4c048c3b1544"),
"userID" : ObjectId("60dee5e1da81bd274cd304de"),
"items" : [
{
"_id" : ObjectId("60ea9fb81b2b4c048c3b1545"),
"product" : {
"_id" : ObjectId("60e62cb21f74572b7c0b3a30"),
"name" : "tv",
"description" : "the best tv",
"categoryID" : 2,
"quantity" : "2",
"serialNumber" : "226swaq12",
"price" : 2000,
"imgUrl" : "https://www.seekpng.com/png/full/774-7744281_samsung-electronics-samsung-electronic-product-png.png"
},
"quantity" : 6,
"createdAt" : ISODate("2021-07-11T07:37:29.790Z"),
"updatedAt" : ISODate("2021-07-11T07:38:15.583Z")
},
{
"_id" : ObjectId("60eaa16b1b2b4c048c3b155d"),
"product" : {
"_id" : ObjectId("60e066009be1060748201ad3"),
"name" : "samsung tv",
"description" : "the best tv",
"quantity" : "2",
"categoryID" : 2,
"serialNumber" : "2212",
"price" : 2000,
"imgUrl" : "https://www.seekpng.com/png/full/774-7744281_samsung-electronics-samsung-electronic-product-png.png"
},
"quantity" : 9,
"updatedAt" : ISODate("2021-07-11T07:46:19.313Z"),
"createdAt" : ISODate("2021-07-11T07:44:43.764Z")
}
],
"createdAt" : ISODate("2021-07-11T07:37:29.792Z"),
"updatedAt" : ISODate("2021-07-11T07:46:19.314Z"),
"__v" : 0
}
I use mongoose.Schema to create new schemas and then when making reference to a different schema I do it like this:
product: { type: mongoose.Schema.Types.ObjectId, ref: 'product' },
If later you need to show also the product info (db.carts.find()), you can use populate() to replace the reference for all the product entries.
You can use upsert true.
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string> // Available starting in MongoDB 4.2
}
)
For example -
db.books.update(
{ item: "ZZZ135" }, // Query parameter
{ // Replacement document
item: "ZZZ135",
stock: 5,
tags: [ "database" ]
},
{ upsert: true } // Options
)
This may help: Mongo Update

How to create new array of object with new key in each object for section list

I have some feature to develop.
I have array with data that contains tasks. Each task have taskEndDate key with value formatted as ( YYYY-MMM-DD ) and it looks like :
[
{
"id": "1616193050660",
"isExpired": false,
"isFinished": false,
"subTasks": [
"Voda redbull ",
"Wiskey Coca-Cola "
],
"taskCreationDate": "2021-Jun-12",
"taskEndDate": 2021-Jun-15,
"taskTitle": "Drink somethig",
"taskType": "BAR"
},
{
"id": "1616193050660",
"isExpired": false,
"isFinished": false,
"subTasks": [
"Voda redbull ",
"Wiskey Coca-Cola "
],
"taskCreationDate": "2021-Jun-12",
"taskEndDate": 2021-Jun-15,
"taskTitle": "Drink somethig",
"taskType": "BAR"
},
{
"id": "1616193050660",
"isExpired": false,
"isFinished": false,
"subTasks": [
"Voda redbull ",
"Wiskey Coca-Cola "
],
"taskCreationDate": "2021-Jun-13",
"taskEndDate": 2021-Jun-18,
"taskTitle": "Drink somethig",
"taskType": "BAR"
}
]
I need to create new array of object that will in next format.
newArray = [{
title: taskEndDate,
data: all tasks that contain same taskEndDate as title
}];
As you can see, the taskEndDate can be same value in few tasks, so I won't to render the title each times, but only once.
For now , I'm doing it hardcoded and then putting the sortedData to <SectionList/>:
const sortedData = [
{
title: 'Previous',
data: data.filter((task) => moment().format('YYYY-MM-DD') > moment(task.taskEndDate).format('YYYY-MM-DD')),
},
{
title: `Today - ${moment().format('MMMM-DD')}`,
data: data.filter((task) => moment().format('YYYY-MM-DD') === moment(task.taskEndDate).format('YYYY-MM-DD')),
},
{
title: 'Tomorrow',
data: data.filter((task) => moment().add(1, 'd').format('YYYY-MM-DD') === moment(task.taskEndDate).format('YYYY-MM-DD')),
},
{
title: moment().add(2, 'd').format('YYYY-MM-DD'),
data: data.filter((task) => moment().add(2, 'd').format('YYYY-MM-DD') === moment(task.taskEndDate).format('YYYY-MM-DD')),
},
{
title: 'Future',
data: data.filter((task) => moment().add(2, 'd').format('YYYY-MM-DD') < moment(task.taskEndDate).format('YYYY-MM-DD')),
},
];
How can I do it generic ti all dates?
Let's consider the data array is sorted by the taskEndDate, then we can achieve grouping the data by taskEndDate as below:
const data = [{..}, {...}] // data array sorted by `taskEndDate`. If not needs to sort the array by taskEndDate before running the forEach loop
let sortedData = []
let length = 0 // length of sortedData
data.forEach(task => {
if(sortedData[length - 1] && task.taskEndDate === sortedData[length - 1].title){
sortedData[length - 1].data.push(task);
}
else{
sortedData.push({title: task.taskEndDate, data: [task] })
++length;
}
})
console.log(sortedData)
Output:
[
{
title: '2021-Jun-15',
data: [
{
id: '1616193050660',
...,
taskCreationDate: '2021-Jun-12',
taskEndDate: '2021-Jun-15',
},
{
id: '1616193050660',
...,
taskCreationDate: '2021-Jun-12',
taskEndDate: '2021-Jun-15',
}
]
},
{
title: '2021-Jun-18',
data: [
{
id: '1616193050660',
...,
taskCreationDate: '2021-Jun-13',
taskEndDate: '2021-Jun-18',
}
]
}
]
I'm not sure if this is what you want. Let me know if this is what you want.
const data = [
{
id: "1616193050660",
isExpired: false,
isFinished: false,
subTasks: ["Voda redbull ", "Wiskey Coca-Cola "],
taskCreationDate: "2021-Jun-12",
taskEndDate: "2021-Jun-15",
taskTitle: "Drink somethig",
taskType: "BAR",
},
{
id: "1616193050660",
isExpired: false,
isFinished: false,
subTasks: ["Voda redbull ", "Wiskey Coca-Cola "],
taskCreationDate: "2021-Jun-12",
taskEndDate: "2021-Jun-15",
taskTitle: "Drink somethig",
taskType: "BAR",
},
{
id: "1616193050660",
isExpired: false,
isFinished: false,
subTasks: ["Voda redbull ", "Wiskey Coca-Cola "],
taskCreationDate: "2021-Jun-13",
taskEndDate: "2021-Jun-18",
taskTitle: "Drink somethig",
taskType: "BAR",
},
];
const sortedData = data.map((data_) => {
return {
title: data_.taskEndDate,
data: data.filter((_task) => data_.taskEndDate === _task.taskEndDate),
};
});
console.log(sortedData);
Ok, I fixed it within the next way :
const getSortedArrayWithTitles = () => {
if (data.length) {
let sortedArray = [
{
title: moment(data[0].taskEndDate).format(appConfig.DAYS_FORMAT),
data: data.filter((task) => moment(task.taskEndDate).format(appConfig.DAYS_FORMAT) === moment(data[0].taskEndDate).format(appConfig.DAYS_FORMAT))
}
];
for (let i = 0, j = 0; i < data.length; i++) {
if (!sortedArray[j].title.includes(moment(data[i].taskEndDate).format(appConfig.DAYS_FORMAT))) {
sortedArray.push(
{
title: moment(data[i].taskEndDate).format(appConfig.DAYS_FORMAT),
data: data.filter((task) => moment(task.taskEndDate).format(appConfig.DAYS_FORMAT) === moment(data[i].taskEndDate).format(appConfig.DAYS_FORMAT))
}
);
j++;
}
}
return sortedArray;
}
};
I'm pretty sure that it is not a best way to use for loop, but It's working fine. Maybe you guys have a better way?

Lodash - Move object to first place in array than sort by another property

I have an array of object employees
{
"emp1": {
"BusinessPartnerFormattedName": "Aleksandra Lewandowski",
"EmpRoleCode": "BUP003",
"EmpRoleType": "Employee",
"EmployeeID": "E8000",
"isAssigned" : true,
"ObjectID": "00163E0E46241ED7A0EA0590D0655967"
},
"emp2": {
"BusinessPartnerFormattedName": "Aleksandra Lewandowski",
"EmpRoleCode": "BUP003",
"EmpRoleType": "Employee",
"EmployeeID": "E8000",
"isAssigned" : true,
"ObjectID": "00163E0E46241ED7A0EA0590D0655967"
},
"emp3": {
"BusinessPartnerFormattedName": "Aleksandra Lewandowski",
"EmpRoleCode": "BUP003",
"EmpRoleType": "Employee",
"EmployeeID": "E8000",
"isAssigned" : false,
"ObjectID": "00163E0E46241ED7A0EA0590D0655967"
},
"emp4": {
"BusinessPartnerFormattedName": " Lewandowski",
"EmpRoleCode": "BUP803",
"EmpRoleType": "Employee",
"EmployeeID": "BUP803",
"isAssigned" : false,
"ObjectID": "00163E0E46241ED7A0EA0590D0655967"
},
"emp5": {
"BusinessPartnerFormattedName": "Aleksandra",
"EmpRoleCode": "BUP043",
"EmpRoleType": "Employee",
"EmployeeID": "BUP043",
"isAssigned" : false,
"ObjectID": "00163E0E46241ED7A0EA0590D0655967"
},
"emp6": {
"BusinessPartnerFormattedName": "Eva Log",
"EmpRoleCode": "BUP0d03",
"EmpRoleType": "Employee",
"EmployeeID": "BUP0d03",
"isAssigned" : false,
"ObjectID": "00163E0E46241ED7A0EA0590D0655967"
}
}
I would like to put the employee where EmployeeID is equal to E8000 first in list , than I want the employee where isAssigned is equal to true to follow
So far I've achieved this :
var sortedItems = _.sortBy(items, function(item) {
return (item.isAssigned === true || item.EmployeeID === "E8000") ? 0 : 1;
});
But how to make sure that the emp with EmployeeID is equal E8000 to will always be on top ?
Not sure why you need lodash on this:
items.sort((a,b)=>{
if(a.EmployeeID !== b.EmployeeID){
if(a.EmployeeID === 'E8000') return -1;
if(b.EmployeeID === 'E8000') return 1;
};
if(a.isAssigned !== b.isAssigned){
return a.isAssigned ? -1 : 1;
}
//Remaining sort logic...
})
This translates to:
"When deciding if a or b should come first, if a and b don't both have the same EmployeeID value, check if either has value E8000. If ether one does have that value, put that one first.
Otherwise, check if a and b have the same value for isAssigned, if they don't, put the one that has true as the isAssigned value first.
Finally if the prior conditions weren't met, follow whatever logic you want for setting which should go first.
Of course, you have to fill in whatever sort logic you want to come after that. For example, if you want to sort alphabetically on BusinessPartnerFormattedName, you'd fill that Remaining sort logic... block with:
if(a.BusinessPartnerFormattedName < b.BusinessPartnerFormattedName) return -1;
if(a.BusinessPartnerFormattedName > b.BusinessPartnerFormattedName) return 1;
return 0;
You chain the wanted sort order.
var array = [
{ name: "E8000 true", EmployeeID: "E8000", isAssigned : true },
{ name: "E8000 true", EmployeeID: "E8000", isAssigned : true },
{ name: "E8003 false", EmployeeID: "E8003", isAssigned : false },
{ name: "E8001 true", EmployeeID: "E8001", isAssigned : true },
{ name: "E8002 true", EmployeeID: "E8002", isAssigned : true },
{ name: "E8001 false", EmployeeID: "E8001", isAssigned : false }
];
array.sort((a, b) =>
(b.EmployeeID === 'E8000') - (a.EmployeeID === 'E8000') ||
b.isAssigned - a.isAssigned
);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
With lodash
var array = [
{ name: "E8000 true", EmployeeID: "E8000", isAssigned : true },
{ name: "E8000 true", EmployeeID: "E8000", isAssigned : true },
{ name: "E8003 false", EmployeeID: "E8003", isAssigned : false },
{ name: "E8001 true", EmployeeID: "E8001", isAssigned : true },
{ name: "E8002 true", EmployeeID: "E8002", isAssigned : true },
{ name: "E8001 false", EmployeeID: "E8001", isAssigned : false }
];
console.log(_.sortBy(array, [
o => o.EmployeeID !== 'E8000',
o => !o.isAssigned
]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
The data you provided is highly misleading, however I still would like to publish my solution, because basically I just like it.
const items = [{BusinessPartnerFormattedName:"Aleksandra Lewandowski",EmpRoleCode:"BUP003",EmpRoleType:"Employee",EmployeeID:"E7000",isAssigned:!0,ObjectID:"00163E0E46241ED7A0EA0590D0655967"},{BusinessPartnerFormattedName:"Aleksandra Lewandowski",EmpRoleCode:"BUP003",EmpRoleType:"Employee",EmployeeID:"E6000",isAssigned:!1,ObjectID:"00163E0E46241ED7A0EA0590D0655967"},{BusinessPartnerFormattedName:"Aleksandra Lewandowski",EmpRoleCode:"BUP003",EmpRoleType:"Employee",EmployeeID:"E8000",isAssigned:!1,ObjectID:"00163E0E46241ED7A0EA0590D0655967"}];
const helper = (emp) => emp.EmployeeID === 'E8000' ? 2 : +(!!emp.isAssigned);
const r = items.sort((a, b) => helper(b) - helper(a));
console.log(r);

Group collection based on the common values of a field mongodb

My collection looks like this
{
"email" : "tp#sd.com",
"subscriptions" : [
{
"default" : false,
"interval" : "weekly",
"tags" : [
{
"name" : "group-1",
"value" : "g1-value-1"
},
{
"name" : "group-1",
"value" : "g1-value-2"
},
{
"name" : "group-2",
"value" : "g2-value-1"
},
{
"name" : "group-3",
"value" : "g3-value-1"
},
{
"name" : "group-3",
"value" : "g3-value-2"
}
]
},
{
"email":"lol#xyz.com",
"subscriptions" : [
{
"default" : false,
"interval" : "weekly",
"tags" : [
{
"name" : "group-1",
"value" : "g1-value-2"
},
{
"name" : "group-1",
"value" : "g1-value-1"
},
{
"name" : "group-2",
"value" : "g2-value-1"
},
{
"name" : "group-2",
"value" : "g2-value-3"
},
{
"name" : "group-3",
"value" : "g3-value-1"
}
]
}
}
I want to group this to an array of objects which contain emails and common group values.
for example, A user-1 has g1-value-1 and user-2 also has g1-value-1, maybe along with other values as well. But these users should be grouped together along with their tags. How do I achieve this?
Surprisingly it's quite an easy query:
db.collection.aggregate([
{
$unwind: "$subscriptions"
},
{
$unwind: "$subscriptions.tags"
},
{
$group: {
_id: "$subscriptions.tags.value",
emails: {$addToSet: "$email"}
}
}
]);
The result will look like this:
[
{
_id: "g1-value-1",
emails: [
"tp#sd.com",
"lol#xyz.com"
]
},
{
_id: "g1-value-2",
emails: [
"tp#sd.com",
"lol#xyz.com"
]
},
{
_id: "g2-value-1",
emails: [
"tp#sd.com",
"lol#xyz.com"
]
},
{
_id: "g2-value-3",
emails: [
"lol#xyz.com"
]
},
{
_id: "g3-value-1",
emails: [
"tp#sd.com",
"lol#xyz.com"
]
},
{
_id: "g3-value-2",
emails: [
"tp#sd.com",
]
},
]

Categories