access to nested array in tabular - tabulator

i have a json array with nested arrays. How can I access them in tabulator
the array contains a list of flights
data = [
flights
flights.price
flights.departure // departure // Frankfurt
flights.arrival // final destination // Houston
flights .... etc
flights.route
flights.route[0].from // flight #1 Frankfurt
flights.route[0].to // flight #1 Washington
flights.route[1].from // flight #2 Washington
flights.route[1].to // flight #2 Houston
....
]
How can i access the route[X].from and list it as value in Tabulator?
I already have read about nested fields (e.g user.name), but how can you access arrays if they have no names but only numbers?

Use data tree for nested data
data:tableDataNested,
dataTree:true,

Related

In Core Data, how sort an NSFetchRequest depending on the sum of an attribute of a child entity? (SwiftUI)

I am building an iOS app in SwiftUI for which I have a Core Data model with two entities:
CategoryEntity with attribute: name (String)
ExpenseEntity with attributes: name (String) and amount (Double)
There is a To-many relationship between CategoryEntity and ExpenseEntity (A category can have many expenses).
I’m fetching the categories and showing them in a list together with the sum of the expenses for each category as follows: Link to app screenshot
I would like to add a sort to the fetch request so the categories appear in order depending on the total amount of their expenses. In the example of the previous picture, the order of appearance that I would like to get would be: Tech, Clothes, Food and Transport. I don’t know how to approach this problem. Any suggestions?
In my current implementation of the request, the sorted is done alphabetically:
// My current implementation for fetching the categories
func fetchCategories() {
let request = NSFetchRequest<CategoryEntity>(entityName: "CategoryEntity")
let sort = NSSortDescriptor(keyPath: \CategoryEntity.name, ascending: true)
request.sortDescriptors = [sort]
do {
fetchedCategories = try manager.context.fetch(request)
} catch let error {
print("Error fetching. \(error.localizedDescription)")
}
}
You don't have to make another FetchRequest, you can just sort in a computed property like this:
(I assume your fetched results come into a var called fetchedCategories.)
var sortedCategories: [CategoryEntity] {
return fetchedCategories.sorted(by: { cat1, cat2 in
cat1.expensesArray.reduce(0, { $0 + $1.amount }) >
cat2.expensesArray.reduce(0, { $0 + $1.amount })
})
}
So this sorts the fetchedCategories array by a comparing rule, that looks at the sum of all cat1.expenses and compares it with the sum of cat2.expenses. The >says we want the large sums first.
You put the computed var directly in the View where you use it!
And where you used fetchedCategories before in your view (e.g. a ForEach), you now use sortedCategories.
This will update in the same way as the fetched results do.
One approach would be to include a derived attribute in your CategoryEntity model description which keeps the totals for you. For example, to sum the relevant values from the amount column within an expenses relation:
That attribute should be updated whenever you save your managed object context. You'll then be able to sort it just as you would any other attribute, without the performance cost of calculating the expense sum for each category whenever you sort.
Note that this option only really works if you don't have to do any filtering on expenses; for example, if you're looking at sorting based on expenses just in 2022, but your core data store also has seconds in 2021, the derived attribute might not give you the sort order you want.

Laravel excel export list in list object maatwebsite/Laravel-Excel

Hi I want to export list of people with all theirs childrens in them to excel. I'm using maatwebsite/Laravel-Excel plugin and its quite easy to export users collection but I need to include users every children inside that row. Its something like [{Name, Age, Gender, Job, Children[{name, age, gender, etc...}], Birthday, etc...}]. And how do I change order of the data column displayed on excel like if I want to switch datas on Age and Gender. Thank you!
You can use WithMapping
https://docs.laravel-excel.com/3.1/exports/mapping.html
<?php
public function map($user): array
{
//create initial array with user data in order that you want columns to be
$data = [
$user->name
...
];
// the same way you should crate headers (if you have). But instead of values you should create column name
foreach($user->children as $child){
array_push($data, $child->name, $child->birthday, $child->...., ..., ...); //and so on
}
// returned data should be 1 level array as each item is a row in the table
return $data;
}

node with mongodb : iterate on distinct result without loading everything into memory

I am discovering node and mongo at the same time and I had one question :
I have a City collection :
{
_id : mongoid
countryId : string
name : string
}
Each city is rattached to one country, and multiple cities can be rattached to the same country. For external reason, this data got corrupted, and some cities have a name equal to null instead of having a valid value (like Paris or London). I need to delete all cities (with a valid name or a null name) for a country where at least one city is having a name equal to null.
For example:
if Country France has only 2 cities (one with name Paris and one with name Marseille), nothing has to be deleted
if Country France has only 2 cities (one with name Paris and one with a name null), both cities have to be deleted
if Country France has only 2 cities (both with null names), both cities have to be deleted
I have managed to do that with the following code (node-mongodb-native 3.1 and node 12.16.1):
const invalidCountryIds = await db.collection('City').distinct('countryId',
{
name:null
}
console.log(invalidCountryIds.length)
invalidCountryIds.forEach(async countryId => {
await db.collection('City').deleteMany({
countryId:countryId
})
I have however 2 questions, this City collection could be possibly very big (more than 10k records) so I wanted to be sure that I was doing that in the most performant way :
when I am calling the .length, am I loading the whole collection of invalidCountryIds into memory
is this foreach the best way to iterate on this collection of invalidCountryIds, I am seeing in documentation that I can also use the .next method available from the cursor object, is there any difference between iterating with this foreach and the next cursor, are both loading into memory only the current element of the collection?
Thanks in advance
You have already loaded the whole result of invalidCountryIds when you query it with await db.collection('City').distinct('countryId', { name: null })
Using cursor, you will load the result to the memory row by row (by default) and you can handle each row. So using cursor will be more memory efficient (not necessarily faster). With queries other than distinct you can also specify the batchSize, the number of documents you will fetch the result from the database each batch.

Why does Core data NSSet invert my array?

I have an array of segments each has an array of fighters associated with it.
The relationship can be described thusly:
One `segment` can have many `fighters`
The objects are managed by core data.
When displayed in a table view each cell has two buttons so a user can pick a fighter from a seperate view controller; and it then when it returns it will update the segment fighter relationship.
Because the relationship of segment.fighters a non-mutable NSSet, I need to modify it so that;
If
User presses left button, this infers that the first object in the segment.fighter is being picked
User presses right button, it infers that the last object in the segment.fighter is being picked
When I come to Update the relationship, sometimes; depending on the sequence of buttons pressed by the user; the positions of the objects in the NSSet are inverted.
ie:
Sometimes a fighter that should be at position 0 is swapped with a
fighter at position 1, when this should never happen.
My code is as follows;
NSArray *currentFighters = [[segment valueForKeyPath:#"fighters"] allObjects];
NSLog(#"----- current fighters ---- ");
for (FCFighter *fighter in currentFighters) {
NSLog(#"%#", [fighter description]);
}
NSMutableArray *currentFightersMutable = [currentFighters mutableCopy];
[currentFightersMutable replaceObjectAtIndex:fighterIdx withObject:pickedFighter];
NSArray *updatedFighters = [currentFightersMutable copy];
NSLog(#"----- updated fighters ---- ");
for (FCFighter *fighter in updatedFighters) {
NSLog(#"%#", [fighter description]);
}
[segment setFighters:[NSSet setWithArray:updatedFighters]];
NSLog(#"----- [segment fighters] ---- ");
for (FCFighter *fighter in [[segment valueForKeyPath:#"fighters"] allObjects]) {
NSLog(#"%#", [fighter description]);
}
I am using a NSMutableArray so that I can replace the exact object in the array.
I can prove that it works via logs
Picked fighter - AJ Fonseca
----- current fighters ----
AJ Matthews
A Sol Kwon
----- updated fighters ----
AJ Fonseca
A Sol Kwon
----- [segment fighters] ---- // NOTE it has swapped them, but why?
A Sol Kwon
AJ Fonseca
-[FCSegmentTableViewCell configureCellWithSegment:]
#0 -- A Sol Kwon
#1 -- AJ Fonseca
However when it gets to segment fighters output, the fighters are swapped; but my question is --
Why does the NSSet invert my array?
Many thanks
An NSSet is an unordered collection of objects. The property allObjects which you use returns an array, but as the documentation for this method states "The order of the objects in the array is undefined.".
Because of this, whenever you try and get an array out of your set, you could get a different order.
To make sure the orders don't change, you should either a) use an ordered relationship for the fighters - but not a good idea as NSOrderedSet is a mix between an array and a set. b) apply a sort to the array returned from allObjects so that the order is consistent. This is my preferred method.

loopback relational database hasManyThrough pivot table

I seem to be stuck on a classic ORM issue and don't know really how to handle it, so at this point any help is welcome.
Is there a way to get the pivot table on a hasManyThrough query? Better yet, apply some filter or sort to it. A typical example
Table products
id,title
Table categories
id,title
table products_categories
productsId, categoriesId, orderBy, main
So, in the above scenario, say you want to get all categories of product X that are (main = true) or you want to sort the the product categories by orderBy.
What happens now is a first SELECT on products to get the product data, a second SELECT on products_categories to get the categoriesId and a final SELECT on categories to get the actual categories. Ideally, filters and sort should be applied to the 2nd SELECT like
SELECT `id`,`productsId`,`categoriesId`,`orderBy`,`main` FROM `products_categories` WHERE `productsId` IN (180) WHERE main = 1 ORDER BY `orderBy` DESC
Another typical example would be wanting to order the product images based on the order the user wants them to
so you would have a products_images table
id,image,productsID,orderBy
and you would want to
SELECT from products_images WHERE productsId In (180) ORDER BY orderBy ASC
Is that even possible?
EDIT : Here is the relationship needed for an intermediate table to get what I need based on my schema.
Products.hasMany(Images,
{
as: "Images",
"foreignKey": "productsId",
"through": ProductsImagesItems,
scope: function (inst, filter) {
return {active: 1};
}
});
Thing is the scope function is giving me access to the final result and not to the intermediate table.
I am not sure to fully understand your problem(s), but for sure you need to move away from the table concept and express your problem in terms of Models and Relations.
The way I see it, you have two models Product(properties: title) and Category (properties: main).
Then, you can have relations between the two, potentially
Product belongsTo Category
Category hasMany Product
This means a product will belong to a single category, while a category may contain many products. There are other relations available
Then, using the generated REST API, you can filter GET requests to get items in function of their properties (like main in your case), or use custom GET requests (automatically generated when you add relations) to get for instance all products belonging to a specific category.
Does this helps ?
Based on what you have here I'd probably recommend using the scope option when defining the relationship. The LoopBack docs show a very similar example of the "product - category" scenario:
Product.hasMany(Category, {
as: 'categories',
scope: function(instance, filter) {
return { type: instance.type };
}
});
In the example above, instance is a category that is being matched, and each product would have a new categories property that would contain the matching Category entities for that Product. Note that this does not follow your exact data scheme, so you may need to play around with it. Also, I think your API query would have to specify that you want the categories related data loaded (those are not included by default):
/api/Products/13?filter{"include":["categories"]}
I suggest you define a custom / remote method in Product.js that does the work for you.
Product.getCategories(_productId){
// if you are taking product title as param instead of _productId,
// you will first need to find product ID
// then execute a find query on products_categories with
// 1. where filter to get only main categoris and productId = _productId
// 2. include filter to include product and category objects
// 3. orderBy filter to sort items based on orderBy column
// now you will get an array of products_categories.
// Each item / object in the array will have nested objects of Product and Category.
}

Resources