Flutter/Dart how to groupBy list of maps - dart

I have this list of maps.
[
{title: 'Avengers', release_date: '10/01/2019'},
{title: 'Creed', release_date: '10/01/2019'}
{title: 'Jumanji', release_date: '30/10/2019'},
]
I would like to write a code that would group the list of movies by release_date like that.
[
{
"10/01/2019": [
{
"title": "Avengers"
},
{
"title": "Creed"
}
]
},
{
"30/10/2019": [
{
"title": "Jumanji"
}
]
}
]

The package collection implements
the groupBy function.
For grouping by date:
import "package:collection/collection.dart";
main(List<String> args) {
var data = [
{"title": 'Avengers', "release_date": '10/01/2019'},
{"title": 'Creed', "release_date": '10/01/2019'},
{"title": 'Jumanji', "release_date": '30/10/2019'},
];
var newMap = groupBy(data, (Map obj) => obj['release_date']);
print(newMap);
}
For removing the release_date key from each map entry:
var newMap = groupBy(data, (Map obj) => obj['release_date']).map(
(k, v) => MapEntry(k, v.map((item) { item.remove('release_date'); return item;}).toList()));
For changing a key:
var newMap = groupBy(data, (Map obj) => obj['release_date']).map(
(k, v) => MapEntry(k, v.map((item) => {'name': item['title']}).toList()));

If you have Dart 2.7, you can extend Iterable to add a useful groupBy method:
extension Iterables<E> on Iterable<E> {
Map<K, List<E>> groupBy<K>(K Function(E) keyFunction) => fold(
<K, List<E>>{},
(Map<K, List<E>> map, E element) =>
map..putIfAbsent(keyFunction(element), () => <E>[]).add(element));
}
Now, you're List of Maps, could be grouped using something like:
final releaseDateMap = listOfMaps.groupBy((m) => m['release_date'])
Data like this:
[
{title: 'Avengers', release_date: '10/01/2019'},
{title: 'Creed', release_date: '10/01/2019'}
{title: 'Jumanji', release_date: '30/10/2019'},
]
would turn into:
{
'10/01/2019': [
{title: 'Avengers', release_date: '10/01/2019'},
{title: 'Creed', release_date: '10/01/2019'}
],
'30/10/2019': [
{title: 'Jumanji', release_date: '30/10/2019'},
]
}

extension UtilListExtension on List{
groupBy(String key) {
try {
List<Map<String, dynamic>> result = [];
List<String> keys = [];
this.forEach((f) => keys.add(f[key]));
[...keys.toSet()].forEach((k) {
List data = [...this.where((e) => e[key] == k)];
result.add({k: data});
});
return result;
} catch (e, s) {
printCatchNReport(e, s);
return this;
}
}
}
then use it like this
var data = [
{"title": 'Avengers', "release_date": '10/01/2019'},
{"title": 'Creed', "release_date": '10/01/2019'},
{"title": 'Jumanji', "release_date": '30/10/2019'},
];
var result = data.groupBy('title');
print(result);
then the result is
[{10/01/2019: [{title: Avengers, release_date: 10/01/2019}, {title: Creed, release_date: 10/01/2019}]}, {30/10/2019: [{title: Jumanji, release_date: 30/10/2019}]}]

I don't know why no one has mentioned that with how basic built-in functions and methods you can achieve it, like:
main() {
List<Map> data = [
{'title': 'Avengers', 'release_date': '10/01/2019'},
{'title': 'Creed', 'release_date': '10/01/2019'},
{'title': 'Jumanji', 'release_date': '30/10/2019'},
];
// Loop through empty {} map and check if the release date exists, if not
// add as the key and empty list as the value, then fill the list with element
// itself, removing 'release_date' before adding. Then you can map the map
// to a list of maps.
List result = data
.fold({}, (previousValue, element) {
Map val = previousValue as Map;
String date = element['release_date'];
if (!val.containsKey(date)) {
val[date] = [];
}
element.remove('release_date');
val[date]?.add(element);
return val;
})
.entries
.map((e) => {e.key: e.value})
.toList();
print(result);
}
Output:
C:\Users\duoqu\Desktop>dart run test.dart
[{10/01/2019: [{title: Avengers}, {title: Creed}]}, {30/10/2019: [{title: Jumanji}]}]

This is a method naively implemented (in case you don't want to use the groupBy function from the collections package):
List<Map<String, List<Map<String, String>>>> MapByKey(String keyName, String newKeyName, String keyForNewName, List<Map<String,String>> input) {
Map<String, Map<String, List<Map<String, String>>>> returnValue = Map<String, Map<String, List<Map<String, String>>>>();
for (var currMap in input) {
if (currMap.containsKey(keyName)) {
var currKeyValue = currMap[keyName];
var currKeyValueForNewName = currMap[keyForNewName];
if (!returnValue.containsKey(currKeyValue)){
returnValue[currKeyValue] = {currKeyValue : List<Map<String, String>>()};
}
returnValue[currKeyValue][currKeyValue].add({newKeyName : currKeyValueForNewName});
}
}
return returnValue.values.toList();
}
void main() {
var test = [
{"title": 'Avengers', "release_date": '10/01/2019'},
{"title": 'Creed', "release_date": '10/01/2019'},
{"title": 'Jumanji', "release_date": '30/10/2019'},
];
var testMapped = MapByKey("release_date", "name", "title", test);
print("$testMapped");
}
The output is:
[
{
10/01/2019: [
{name: Avengers
},
{name: Creed
}
]
},
{
30/10/2019: [
{name: Jumanji
}
]
}
]

To add to the accepted answer if you come arcross this, In flutter 2, you will Get an error, as i got.
The operator '[]' isn't defined for the type 'dynamic Function(dynamic)'
Use
var data = [
{"title": 'Avengers', "release_date": '10/01/2019'},
{"title": 'Creed', "release_date": '10/01/2019'},
{"title": 'Jumanji', "release_date": '30/10/2019'},
];
var newMap = groupBy(data, (Map oj) => oj['release_date']);
print(newMap);
This might be of help to someone.

Using the supercharged package, you'd write it like this:
List list = [
{ title: 'Avengers', release_date: '10/01/2019' },
{ title: 'Creed', release_date: '10/01/2019' }
{ title: 'Jumanji', release_date: '30/10/2019' },
];
final map = list.groupBy<String, Map>((item) =>
item['release_date'],
valueTransform: (item) => item..remove('release_date'),
);

It may not be the best solution. But it can give you an idea
List arrayData = [
{"name": 'John', "gender": 'male'},
{"name": 'James', "gender": 'male'},
{"name": 'Mary', "gender": 'female'}
];
Retrieve list ​​by gender:
List males = arrayData.where((o) => o['gender'] == "male").toList();
List females = arrayData.where((o) => o['gender'] == "female").toList();
Make new map with desired format:
List result = [
{
"male": males.map((f) => {"name": f['name']}).toList()
},
{
"female": females.map((f) => {"name": f['name']}).toList()
}
];
print:
debugPrint('${result}');
result:
[{male: [{name: John}, {name: James}]}, {female: [{name: Mary}]}]

Related

Merge object and add keys from JSON format using Ruby on Rails

I have a list of array that is queried that needs to be merged with the same location_id based on the objects.
**this are the code for generating array **
filled = Product.on_hand_location(pid).to_a
empty = Product.on_hand_location_empty_cylinder(pid).to_a
data = filled + empty
result = data.map{ |k|
{
details: {
location_id: k['location_id'],
"location_name"=>k['location_name'],
"onhandcylynder"=>k['onhand'] == nil ? 0 : k['onhand'],
"emptycylynder"=> k['emptyonhand'] == nil ? 0 : k['emptyonhand']
} ,
}
}
respond_with [ onhand: result ]
This JSON format below is the output of code above. which has location_id that needs to be merge
[{
"onhand": [{
"details": {
"location_id": 1,
"location_name": "Capitol Drive",
"onhandcylynder": "4.0",
"emptycylynder": 0
}
},
{
"details": {
"location_id": 2,
"location_name": "SM City Butuan",
"onhandcylynder": "5.0",
"emptycylynder": 0
}
},
{
"details": {
"location_id": 1,
"location_name": null,
"onhandcylynder": 0,
"emptycylynder": "2.0"
}
}
]
}]
My desired output
[{
"onhand": [{
"details": {
"location_id": 1,
"location_name": "Capitol Drive",
"onhandcylynder": "4.0",
"emptycylynder": 0
}
},
{
"details": {
"location_id": 2,
"location_name": "SM City Butuan",
"onhandcylynder": "5.0",
"emptycylynder": "2.0"
}
}
]
}]
I think instead of data = filled + empty you should try
data = Product.on_hand_location(pid).to_a
empty = Product.on_hand_location_empty_cylinder(pid).to_a
empty.each do |location|
data.push(location) if data.none? { |item| item['location_id'] == product['location_id'] }
end
result = ...
or
hash = {}
Product.on_hand_location_empty_cylinder(pid).map { |l| hash[l['location_id']] = l }
Product.on_hand_location(pid).map { |l| hash[l['location_id']] = l }
data = hash.values
and if you need some data from both of the queries you should try
hash = {}
Product.on_hand_location_empty_cylinder(pid).map { |l| hash[l['location_id']] = l }
Product.on_hand_location(pid).map { |l| hash[l['location_id']].merge!(l) }
data = hash.values
to merge in place
I refactor my code and able to get my desired result
filled = Product.on_hand_location(pid).to_a
emptyTank = Product.on_hand_location_empty_cylinder(pid).to_a
data = filled + emptyTank
cylinder = data.map(&:dup)
.group_by { |e| e.delete('location_id') }
finalResult = cylinder.map{|_, location_id | location_id.reduce({}) { |result, location_id|
result.merge(location_id)
} }
respond_with [ onhand: finalResult]
The result already merge with the same location id and emptyonhand keys are merge already in corresponding to its location ID
[
{
"onhand": [
{
"onhand": "1.0",
"location_name": "Capitol Drive",
"emptyonhand": "5.0"
},
{
"onhand": "5.0",
"location_name": "SM City Butuan"
}
]
}
]

Dinamic table with PdfMake

It dont display in format. I'm using Angular 8.
This part is for getting the info.
var med = MyData....;//[name,price,description]
var col = [];
med.forEach(element => {
var row=[];
row.push([element.name]);
row.push([element.price])
row.push([element.description]);
console.log(row);
col.push(row);
});
then this part is for displaying in pdfMake
let dd= {
content: [
{
table: {
`body`: [
col
]
},
}
]
}
Sometimes it displays vertically.
In pdfmake.org/playground.html when you put this code:
var ex = [['example 1', '10','d1'],['example 2', '12','d2'], ['example 3', '18','d3']];
var dd = {
content: [
{
style: 'tableExample',
table: {
widths:['auto','auto','*'],
body: [
['name', 'price ','description'],
ex
]
}
},
]
}
this is te result:
and I need something like this, no matter how much values I get in my array:
var ex = [['example 1', '10','d1'],['example 2', '12','d2'], ['example 3', '18','d3']];
var dd = {
content: [
{
style: 'tableExample',
table: {
widths:['auto','auto','*'],
body: [
['name', 'price ','description'],
ex[0],
ex[1],
ex[2]
]
}
},
]
}
I need this result:

Cypher request to Generate a nested recursive json

So far I have created the following nodes:
CREATE
(b:Brand {identifier: 'ANTIINFECTIEUX',brand:'ANTIINFECTIEUX',description :'ANTIINFECTIEUX' }),
(b)<-[:IS_A_CATALOG_BELONGING_TO]-(c:Catalog {identifier: 'ANTIBACTERIENS',catalogName:'ANTIBACTERIENS',brand:'ANTIINFECTIEUX',brandIdentifier:'ANTIINFECTIEUX',description :'ANTIBACTERIENS'}),
(c)<-[:IS_A_PRODUCT_BELONGING_TO_THAT_CATALOG]-(p:Product {identifier: 'Amikacine',productName:'Amikacine',brand:'ANTIINFECTIEUX',brandIdentifier:'ANTIINFECTIEUX',catalog:'ANTIBACTERIENS',catalogIdentifier:'ANTIBACTERIENS',description :'Amikacine',DCI:'Amikacine', Dosage:'1g', Forme:'Inj', Case:'false', Poste:'false', CTRE:'false', CHR:'true', CHN:'true', Reference:'Amiklin', price:'200.75', stock:'500',NumeroDeLot:'87',CodeBarre:'87878787878787878',QuantiteDemandee:'50'}),
(p)-[:IS_A_PRODUCT_BELONGING_TO_THAT_BRAND]->(b),
(c)<-[:IS_A_PRODUCT_BELONGING_TO_THAT_CATALOG]-(p2:Product {identifier: 'Amoxicilline',productName:'Amoxicilline',brand:'ANTIINFECTIEUX',brandIdentifier:'ANTIINFECTIEUX',catalog:'ANTIBACTERIENS',catalogIdentifier:'ANTIBACTERIENS',description :'Amoxicilline',DCI:'Amoxicilline', Dosage:'500mg', Forme:'Gélules', Case:'false', Poste:'true', CTRE:'true', CHR:'true', CHN:'true', Reference:'Clamoxyl', price:'250.75', stock:'700',NumeroDeLot:'8777',CodeBarre:'998898979797',QuantiteDemandee:'50'}),
(p2)-[:IS_A_PRODUCT_BELONGING_TO_THAT_BRAND]->(b),
(b1:Brand {identifier: 'ANESTHESIQUES',brand:'ANESTHESIQUES',description :'ANESTHESIQUES' }),
(b1)<-[:IS_A_CATALOG_BELONGING_TO]-(c1:Catalog {identifier: 'Anesthesiques_Generaux_et_Gaz_medicaux',catalogName:'Anesthesiques_Generaux_et_Gaz_medicaux',brand:'ANESTHESIQUES',brandIdentifier:'ANESTHESIQUES',description :'Anesthésiques généraux et Gaz médicaux'}),
(c1)<-[:IS_A_PRODUCT_BELONGING_TO_THAT_CATALOG]-(p1:Product {identifier: 'Kétamine',productName:'Kétamine',brand:'ANESTHESIQUES',brandIdentifier:'ANESTHESIQUES',catalog:'Anesthesiques_Generaux_et_Gaz_medicaux',catalogIdentifier:'Anesthesiques_Generaux_et_Gaz_medicaux',description :'Kétamine',DCI:'Kétamine', Dosage:'50mg/amp', Forme:'Inj', Case:'false', Poste:'false', CTRE:'true', CHR:'true', CHN:'true', Reference:'Kétalar', price:'900.75', stock:'300',NumeroDeLot:'677',CodeBarre:'5454578788',QuantiteDemandee:'10'}),
(p1)-[:IS_A_PRODUCT_BELONGING_TO_THAT_BRAND]->(b1)
The purpose is to get a nested json like this:
{
"menuItems":[
{
"name":"Anesthesiques_Generaux_et_Gaz_medicaux",
"children":[
{
"name":"ANESTHESIQUES",
"children":[
{
"name":"Kétamine",
"ProductCHR":"true",
"ProductForme":"Inj",
"ProductCHN":"true",
"ProductReference":"Kétalar",
"ProductDCI":"Kétamine",
"ProductCase":"false",
"ProductDosage":"50mg/amp",
"ProductIdentifier":"Kétamine",
"ProductPoste":"false",
"ProductPrice":"900.75",
"ProductCTRE":"true",
"ProductStock":"300"
}
]
}
]
},
{
"name":"ANTIBACTERIENS",
"children":[
{
"name":"ANTIINFECTIEUX",
"children":[
{
"name":"Amikacine",
"ProductCHR":"true",
"ProductForme":"Inj",
"ProductCHN":"true",
"ProductReference":"Amiklin",
"ProductDCI":"Amikacine",
"ProductCase":"false",
"ProductDosage":"1g",
"ProductIdentifier":"Amikacine",
"ProductPoste":"false",
"ProductPrice":"200.75",
"ProductCTRE":"false",
"ProductStock":"500"
},
{
"name":"Amoxicilline",
"ProductCHR":"true",
"ProductForme":"Gélules",
"ProductCHN":"true",
"ProductReference":"Clamoxyl",
"ProductDCI":"Amoxicilline",
"ProductCase":"false",
"ProductDosage":"500mg",
"ProductIdentifier":"Amoxicilline",
"ProductPoste":"true",
"ProductPrice":"250.75",
"ProductCTRE":"true",
"ProductStock":"700"
}
]
}
]
}
]
}
To generate that JSON file I've made the following cypher request:
MATCH (Brand:Brand)
OPTIONAL MATCH (Brand)<-[:IS_A_CATALOG_BELONGING_TO]-(Catalog:Catalog)
OPTIONAL MATCH (Catalog)<-[:IS_A_PRODUCT_BELONGING_TO_THAT_CATALOG]-(Product:Product)
OPTIONAL MATCH (Product)-[:IS_A_PRODUCT_BELONGING_TO_THAT_BRAND]->(Brand)
WITH Brand, Catalog, Product
ORDER BY Product.identifier ASC
WITH Brand, Catalog,
collect({name: Product.DCI, ProductIdentifier:Product.identifier,ProductDCI:Product.DCI,
ProductDosage:Product.Dosage,ProductForme:Product.Forme,ProductCase:Product.Case,
ProductPoste:Product.Poste,ProductCTRE:Product.CTRE,ProductCHR:Product.CHR,ProductCHN:Product.CHN,
ProductReference:Product.Reference,ProductPrice:Product.price,ProductStock:Product.stock,
NumeroDeLot:Product.NumeroDeLot,CodeBarre:Product.CodeBarre,QuantiteDemandee:Product.QuantiteDemandee}) AS pNames
ORDER BY Catalog.identifier ASC
WITH Brand.identifier AS name,
collect(Catalog.identifier ) AS cname,
collect( pNames) AS children
ORDER BY name ASC
RETURN apoc.convert.toJson({name:name,cname:cname,children:children})
That request holds all infos need but
Unfortunately, the ideal output form it doesn't match my expectations (the resultant json that I really want) as you can see here.
"{
"children":[
[
{
"NumeroDeLot":"677",
"ProductReference":"Kétalar",
"ProductCase":"false",
"ProductPrice":"900.75",
"ProductCTRE":"true",
"QuantiteDemandee":"10",
"ProductCHR":"true",
"ProductForme":"Inj",
"ProductCHN":"true",
"ProductDCI":"Kétamine",
"ProductDosage":"50mg/amp",
"ProductIdentifier":"Kétamine",
"name":"Kétamine",
"ProductPoste":"false",
"CodeBarre":"5454578788",
"ProductStock":"300"}
]
],
"name":"ANESTHESIQUES",
"cname":["Anesthesiques_Generaux_et_Gaz_medicaux"]
}
"
"{
"children":[
[
{
"NumeroDeLot":"87",
"ProductReference":"Amiklin",
"ProductCase":"false",
"ProductPrice":"200.75",
"ProductCTRE":"false",
"QuantiteDemandee":"50",
"ProductCHR":"true",
"ProductForme":"Inj",
"ProductCHN":"true",
"ProductDCI":"Amikacine",
"ProductDosage":"1g",
"ProductIdentifier":"Amikacine",
"name":"Amikacine",
"ProductPoste":"false",
"CodeBarre":"87878787878787878",
"ProductStock":"500"
},
{
"NumeroDeLot":"8777",
"ProductReference":"Clamoxyl",
"ProductCase":"false",
"ProductPrice":"250.75",
"ProductCTRE":"true",
"QuantiteDemandee":"50",
"ProductCHR":"true",
"ProductForme":"Gélules",
"ProductCHN":"true",
"ProductDCI":"Amoxicilline",
"ProductDosage":"500mg",
"ProductIdentifier":"Amoxicilline",
"name":"Amoxicilline",
"ProductPoste":"true",
"CodeBarre":"998898979797",
"ProductStock":"700"
}
]
],
"name":"ANTIINFECTIEUX",
"cname":["ANTIBACTERIENS"]
}"
It would be great if someone could help me to achieve that purpose.
{
"menuItems":[
{
"name":"Brand Name1",
"children":[
{
"name":"Catalog Name",
"children":[
{
"name": "productName1",
.....................
etc
},
{
"name": "productName2"
.....................
},
........................
{
"name": "productNameN"
.....................
}
]
},
......................................
{
"name":"Catalog NameN",
"children":[
{
"name": "productName1ForCatalogNameN",
.....................
etc
},
{
"name": "productName2ForCatalogNameN"
.....................
},
........................
{
"name": "productNameNForCatalogNameN"
.....................
}
]
},
]
},
....................................................................
{
"name":"Brand NameN",
"children":[
{
"name":"Catalog Name",
"children":[
{
"name": "productName1",
.....................
etc
},
{
"name": "productName2"
.....................
},
........................
{
"name": "productNameN"
.....................
}
]
},
......................................
{
"name":"Catalog NameN",
"children":[
{
"name": "productName1ForCatalogNameN",
.....................
etc
},
{
"name": "productName2ForCatalogNameN"
.....................
},
........................
{
"name": "productNameNForCatalogNameN"
.....................
}
]
},
]
}
]
}
Many thanks.
CREATE
(b:Brand {name: 'ANTIINFECTIEUX',brand:'ANTIINFECTIEUX',description :'ANTIINFECTIEUX' }),
(b)<-[:IS_A_CATALOG_BELONGING_TO]-(c:Catalog {name: 'ANTIBACTERIENS',catalogName:'ANTIBACTERIENS',brand:'ANTIINFECTIEUX',brandIdentifier:'ANTIINFECTIEUX',description :'ANTIBACTERIENS'}),
(c)<-[:IS_A_PRODUCT_BELONGING_TO_THAT_CATALOG]-(p:Product {name: 'Amikacine',productName:'Amikacine',brand:'ANTIINFECTIEUX',brandIdentifier:'ANTIINFECTIEUX',catalog:'ANTIBACTERIENS',catalogIdentifier:'ANTIBACTERIENS',description :'Amikacine',DCI:'Amikacine', Dosage:'1g', Forme:'Inj', Case:'false', Poste:'false', CTRE:'false', CHR:'true', CHN:'true', Reference:'Amiklin', price:'200.75', stock:'500',NumeroDeLot:'87',CodeBarre:'87878787878787878',QuantiteDemandee:'50'}),
(p)-[:IS_A_PRODUCT_BELONGING_TO_THAT_BRAND]->(b),
(c)<-[:IS_A_PRODUCT_BELONGING_TO_THAT_CATALOG]-(p2:Product {name: 'Amoxicilline',productName:'Amoxicilline',brand:'ANTIINFECTIEUX',brandIdentifier:'ANTIINFECTIEUX',catalog:'ANTIBACTERIENS',catalogIdentifier:'ANTIBACTERIENS',description :'Amoxicilline',DCI:'Amoxicilline', Dosage:'500mg', Forme:'Gélules', Case:'false', Poste:'true', CTRE:'true', CHR:'true', CHN:'true', Reference:'Clamoxyl', price:'250.75', stock:'700',NumeroDeLot:'8777',CodeBarre:'998898979797',QuantiteDemandee:'50'}),
(p2)-[:IS_A_PRODUCT_BELONGING_TO_THAT_BRAND]->(b),
(b1:Brand {name: 'ANESTHESIQUES',brand:'ANESTHESIQUES',description :'ANESTHESIQUES' }),
(b1)<-[:IS_A_CATALOG_BELONGING_TO]-(c1:Catalog {name: 'Anesthesiques_Generaux_et_Gaz_medicaux',catalogName:'Anesthesiques_Generaux_et_Gaz_medicaux',brand:'ANESTHESIQUES',brandIdentifier:'ANESTHESIQUES',description :'Anesthésiques généraux et Gaz médicaux'}),
(c1)<-[:IS_A_PRODUCT_BELONGING_TO_THAT_CATALOG]-(p1:Product {name: 'Kétamine',productName:'Kétamine',brand:'ANESTHESIQUES',brandIdentifier:'ANESTHESIQUES',catalog:'Anesthesiques_Generaux_et_Gaz_medicaux',catalogIdentifier:'Anesthesiques_Generaux_et_Gaz_medicaux',description :'Kétamine',DCI:'Kétamine', Dosage:'50mg/amp', Forme:'Inj', Case:'false', Poste:'false', CTRE:'true', CHR:'true', CHN:'true', Reference:'Kétalar', price:'900.75', stock:'300',NumeroDeLot:'677',CodeBarre:'5454578788',QuantiteDemandee:'10'}),
(p1)-[:IS_A_PRODUCT_BELONGING_TO_THAT_BRAND]->(b1)
The request that fulfilled my needs
MATCH PATH = (Brand:Brand)<-[*]-(Catalog:Catalog)<-[*]-(Product:Product)
with collect(PATH) as paths
call apoc.convert.toTree(paths) yield value
return value
From neo4j 3.5.0 + and up the signature of apoc.convert.toTree
we could include/exclude properties,relationships and as has 3 arguments
[paths],[lowerCaseRels=true]) | creates a stream of nested documents representing the at least one root of these paths
like in the below
To exclude we prefix with -
apoc.convert.toTree(ps, true,{nodes: {Catalog: ['-name']},
relationships: {subcategory:['-id']}})
To include
apoc.convert.toTree(ps, true,{nodes: {Catalog: ['name']},
relationships: {subcategory:['id']}})
but Unfortunately there is no way to remove _id _type from cypher result See that link [https://stackoverflow.com/questions/56288402/is-there-a-way-to-remove-id-type-from-cypher-result]1

Access nested JSON property in jspdf autotable plugin

I have just started using jsPDF and the AutoTable plugin, and it is almost perfect for what we are using it for. One question...
Is it possible to assign a dataKey in the columns definition to a nested property within the JSON that is being mapped to the table?
We have a JSON structure that looks like this:
"Primary_Key": "12345",
"Site_Name": {
"Address_Name": "Address 1"
},
"Default_Screen_Name": "Bob",
"Full_Name": "Bob Smith"
If we use the following columns:
var columns = [
{ title: "ID", dataKey: "Primary_Key" },
{ title: "Screen Name", dataKey: "Default_Screen_Name" },
{ title: "Full Name", dataKey: "Full_Name" }];
Everything works perfectly. However, we would also like to do something like the following:
var columns = [
{ title: "ID", dataKey: "Primary_Key" },
{ title: "Iterations", dataKey: "Iterations" },
{ title: "Screen Name", dataKey: "Default_Screen_Name" },
{ title: "Site Name", dataKey: "Site_Name.Address_Name" }];
Where we are using Site_Name.Address_Name to index into the nested JSON object to retrieve the value.
Is something like this possible?
Not at the moment. You can follow that feature request here. Your options are currently to either flatten the data before passing it to autotable or use the hooks to extract the specific text you want. That can be done like this:
var columns = [
{title: "ID", dataKey: "id"},
{title: "Name", dataKey: "name"},
{title: "Country", dataKey: "address"}
];
var rows = [
{id: 1, name: "Shaw", address: {country: "Tanzania"}},
{id: 2, name: "Nelson", address: {country: "Kazakhstan"}},
{id: 3, name: "Garcia", address: {country: "Madagascar"}}
];
var doc = jsPDF();
doc.autoTable(columns, rows, {
didParseCell: function(data) {
if (data.column.dataKey === 'address') {
data.cell.text = data.cell.raw.country;
}
}
});
doc.save('table.pdf');
<script src="https://unpkg.com/jspdf#1.3.3/dist/jspdf.min.js"></script>
<script src="https://unpkg.com/jspdf-autotable#2.3.1/dist/jspdf.plugin.autotable.js"></script>
Update for additional question in comments:
var columns = [
{title: "Country", dataKey: "address", displayProperty: "country"},
...
];
var rows = [...];
...
didParseCell: function(data) {
if (data.column.dataKey === 'address') {
var prop = data.column.raw.displayProperty;
data.cell.text = data.cell.raw[prop];
}
}

How to extract a list of proplists {K,V} from any complex Term

Having a Term that may consist of anything such as orddicts, lists of orddicts, orddicts of orddicts, list of lists, proplists of orddicts or ... such as:
Term1 = [
{"AAA", [
{ "K1", "ka1" },
{ "K2", "ka2" },
{ "K3", "ka3" }
]
},
{"BBB","one"},
{"CCC", [
{ "K1", "kb1" },
{ "K2", "" },
{ "K3", "kb3" }
]
},
{"DDD", [
[
{ "K1", "kc1" },
{ "K2", "kc2" }
],
[
{ "K1", "kd1" },
{ "K2", "kd2" }
],
"CACETA",
123
]
},
{"EEE", [
{ "K1", "kb1" },
{ "K2", 1122 },
{ "K3", "kb3" }
]
},
{ "T1", "T2", "T3" },
123,
{ "X" },
[ 1, 2, 3, { "K5", "V5" } ]
],
I would need to produce a list of all proplists [{K,V},...] such as
[
{ "AAA" , [ ...... ] },
{ "K1" , "ka1" },
{ "K2" , "ka2" },
...
{ "BBB" ,"one"},
{ "CCC" , [ ... ] },
{ "K1" , "kb1" },
...
{ "K5", "V5" }
]
notice that there are keys that must repeat along the list, their value may be a string, a list, a tupple or number, anything.
the last items in the data in the example above, such as { "T1", "T2", "T3" } should not be in the result since it is not a proplist of two terms { K, V}, but the nested { "K5", "V5" } is and should be part of the result.
I looked at this similar solution and tried to tune it up a little bit, but it is getting hard for my novice erlang brain to get it to work with my scenario above.
Here is an example of what I am trying to use to make it work, but there are some errors, pattern matching related:
extractPropList( [], ResultList ) -> ResultList;
extractPropList( [H|T], ResultList ) -> extractPropList(T, extractPropList(H, ResultList));
extractPropList( {K,V}, ResultList ) -> [ {K,V} | extractPropList(K, extractPropList(V, ResultList)) ].
While testing the above approach, the missing part was the last row that treats a term that had no other matching ( not a list, not a {K,V} ):
extractPropLists( [], ResultList ) -> ResultList;
extractPropLists( [H|T], ResultList ) -> extractPropLists(T, extractPropLists(H, ResultList));
extractPropLists( {K,V}, ResultList ) -> [ {K,V} | extractPropLists(K, extractPropLists(V, ResultList)) ];
extractPropLists( T, ResultList ) -> ResultList.
Given data similar to the avove, the results I obtained where
[{"EEE",[{"K1","kb1"},{"K2",1122},{"K3","kb3"}]},
{"K3","kb3"},
{"K2",1122},
{"K1","kb1"},
{"DDD",
[[{"K1","kc1"},{"K2","kc2"}],
[{"K1","kd1"},{"K2","kd2"}],
"CACETA",123]},
{"K2","kd2"},
{"K1","kd1"},
{"K2","kc2"},
{"K1","kc1"},
{"CCC",[{"K1","kb1"},{"K2","kb2"},{"K3","kb3"}]},
{"K3","kb3"},
{"K2","kb2"},
{"K1","kb1"},
{"BBB","one"},
{"AAA",[{"K1","ka1"},{"K2","ka2"},{"K3","ka3"}]},
{"K3","ka3"},
{"K2","ka2"},
{"K1","ka1"}]

Resources