How to use where method with null boolean - flutter

I have a list like this:
[
{'country': ' Wakanda', 'languages': null},
{
'country': 'USA',
'languages': [
{'language': 'English'}
]
},
{
'country': 'Germany',
'languages': [
{'language': 'German'}
]
},
{
'country': ' Ireland',
'languages': [
{'language': 'English'},
{'language': 'Irish'}
]
}
]
I try to create a new list that 'language' contains 'eng'toLowwerCase(), but the error is Failed assertion: boolean expression must not be null
So pls help me, this is the full code:
void main() async {
List list = [
{'country': ' Wakanda', 'languages': null},
{
'country': 'USA',
'languages': [
{'language': 'English'}
]
},
{
'country': 'Germany',
'languages': [
{'language': 'German'}
]
},
{
'country': ' Ireland',
'languages': [
{'language': 'English'},
{'language': 'Irish'}
]
}
];
List filterList = List.from(list).where((e) {
return e['languages']?.any((l) => l['language'].toLowwerCase().contains('eng').toLowwerCase());
}).toList();
print(filterList);
}

The callback to Iterable.where must return a non-nullable bool type. Your callback potentially returns null if e['languages'] returns null:
return e['languages']?.any(
(l) => l['language'].toLowwerCase().contains('eng').toLowwerCase()
);
The way to fix it is to handle null. You can use x ?? y to provide a default value of y if x is null:
return e['languages']?.any(
(l) => l['language'].toLowwerCase().contains('eng').toLowwerCase()
) ?? false;
I'll also point out that:
toLowerCase() is misspelled.
List.from(list).where(...).toList() is redundant and could be just list.where(...).toList().

Try something like this
List filterList = List.from(list).where((e) {
// Avoid check null valĂșes
if (e['languages'] == null) {
return false;
}
return e['languages']?.any(
(l) => l['language'].toLowwerCase().contains('eng').toLowwerCase());
}).toList();
Also you can validate language child value

void main() async {
List list = [
{'country': ' Wakanda', 'languages': null},
{
'country': 'USA',
'languages': [
{'language': 'English'}
]
},
{
'country': 'Germany',
'languages': [
{'language': 'German'}
]
},
{
'country': ' Ireland',
'languages': [
{'language': 'English'},
{'language': 'Irish'}
]
}
];
List filterList = List.from(list).where((e) {
try{
return e['languages']?.any((l) =>
l['language'].toLowwerCase().contains('eng').toLowwerCase());
}).toList();
}
catch(e){
return [''];
}
print(filterList);
}

Related

How to iterate a particular item on a JSON list in flutter?

How can I print out only the lnames from the JSON list? The code below is an example.
void main() {
// int index = 0;
List sample = [
{
'fname': 'sellerA',
'lname': 'bola',
'companyName': 'Faithtuts',
'country': 'Nigeria',
},
{
'fname': 'sellerB',
'lname': 'abbey',
'companyName': 'Xerox',
'country': 'Dubai',
},
{
'fname': 'sellerC',
'lname': 'grace',
'companyName': 'Nebrob',
'country': 'Japan',
},
];
for(int index = 0; index < sample.length; index++){
var getCName = sample.map((e) => sample[index]['lname']);
print('$getCName');
}
}
The Result:
(bola, bola, bola)
(abbey, abbey, abbey)
(grace, grace, grace)
But I am looking to get something like this instead. (bola, abbey, grace)
By combining your for loop with map, you are iterating twice on your list.
Instead, try this:
for(int index = 0; index < sample.length; index++) {
var getCName = sample[index]['lname'];
print('$getCName');
}
Or:
for(final element in sample) {
var getCName = element['lname'];
print(getCName);
}
Or, simply:
sample.map((element) => element['lname']).forEach(print);
Full example
void main() {
List sample = [
{
'fname': 'sellerA',
'lname': 'bola',
'companyName': 'Faithtuts',
'country': 'Nigeria',
},
{
'fname': 'sellerB',
'lname': 'abbey',
'companyName': 'Xerox',
'country': 'Dubai',
},
{
'fname': 'sellerC',
'lname': 'grace',
'companyName': 'Nebrob',
'country': 'Japan',
},
];
sample.map((element) => element['lname']).forEach(print);
}
This prints the following to the console:
bola
abbey
grace

How to unwind/merge arrays from hierarchical document structure?

I have a nested document structure and I am able to filter it with pluck to show the relevant parts:
Is there an elegant way to merge all entries of the last level to a single array?
Expected result (entries are not unique on purpose):
[
'3425b91f-f019-4db3-ad56-c336bf55279b',
'3d07946e-183d-4992-9acd-676f5122e1b1',
'3425b91f-f019-4db3-ad56-c336bf55279b',
'3d07946e-183d-4992-9acd-676f5122e1b1',
'2cd652a6-4dcd-4920-9592-d4cdc5a034bf',
'70fe1812-e1de-447b-ac4f-d89fead4756d',
'2cd652a6-4dcd-4920-9592-d4cdc5a034bf',
'70fe1812-e1de-447b-ac4f-d89fead4756d'
]
I tried to use
r.table('periods')['regions']['sites']['plants']['product']['process']['technologies'].run()
but it gives the error "Cannot perform bracket on a sequence of sequences".
=> Is there some alternative operator to get a merged sequence instead a "sequence of sequences" for each step?
Something like
r.table('periods').unwind('regions.sites.plants.product.process.technologies')
Here is some python code to create example data:
from rethinkdb import RethinkDB
r = RethinkDB()
r.connect({}).repl()
r.table_create("periods")
def uniqueid():
return r.uuid().run()
periodid_first = uniqueid()
periodid_second = uniqueid()
companyid_2000 = uniqueid()
companyid_2001 = uniqueid()
technologyid_2000_first = uniqueid()
technologyid_2000_second = uniqueid()
technologyid_2001_first = uniqueid()
technologyid_2001_second = uniqueid()
energy_carrierid_2000_first = uniqueid()
energy_carrierid_2000_second = uniqueid()
energy_carrierid_2001_first = uniqueid()
energy_carrierid_2001_second = uniqueid()
periods = [
{
'id': periodid_first,
'start': 2000,
'end': 2000,
# 'sub_periods': [],
'regions': [
{
'id': 'DE',
# 'sub_regions': [],
'sites': [
{
'id': 'first_site_in_germany',
'company': companyid_2000, # => verweist auf periods => companies
'plants': [
{
'id': 'qux',
'product': {
'id': 'Ammoniak',
'process': {
'id': 'SMR+HB',
'technologies': [
technologyid_2000_first, # => verweist auf periods => technologies
technologyid_2000_second
]
}
}
}
]
}
]
},
{
'id': 'FR',
# 'sub_regions': [],
'sites': [
{
'id': 'first_site_in_france',
'company': companyid_2000, # => verweist auf periods => companies
'plants': [
{
'id': 'qux',
'product': {
'id': 'Ammoniak',
'process': {
'id': 'SMR+HB',
'technologies': [
technologyid_2000_first, # => verweist auf periods => technologies
technologyid_2000_second
]
}
}
}
]
}
]
}
],
'companies': [
{
'id': companyid_2000,
'name': 'international_company'
}
],
'technologies': [
{
'id': technologyid_2000_first,
'name': 'SMR',
'specific_cost_per_year': 123,
'specific_energy_consumptions': [
{
'energy_carrier': energy_carrierid_2000_first,
'specific_consumption': 5555
}, # => verweist auf periods => energy_carriers
{
'energy_carrier': energy_carrierid_2000_second,
'energy_consumption': 2333
}
]
},
{
'id': technologyid_2000_second,
'name': 'HB',
'specific_cost_per_year': 1234,
'specific_energy_consumptions': [
{
'energy_carrier': energy_carrierid_2000_first,
'specific_consumption': 555
}, # => verweist auf periods => energy_carriers
{
'energy_carrier': energy_carrierid_2000_second,
'energy_consumption': 233
}
]
}
],
'energy_carriers': [
{
'id': energy_carrierid_2000_first,
'name': 'oil',
'group': 'fuel'
},
{
'id': energy_carrierid_2000_second,
'name': 'gas',
'group': 'fuel'
},
{
'id': uniqueid(),
'name': 'conventional',
'group': 'electricity'
},
{
'id': uniqueid(),
'name': 'green',
'group': 'electricity'
}
],
'networks': [
{
'id': uniqueid(),
'name': 'gas',
'sub_networks': [],
'pipelines': [
]
},
{
'id': uniqueid(),
'name': 'gas',
'sub_networks': [],
'pipelines': [
]
}
]
},
{
'id': periodid_second,
'start': 2001,
'end': 2001,
# 'sub_periods': [],
'regions': [
{
'id': 'DE',
# 'sub_regions': [],
'sites': [
{
'id': 'first_site_in_germany',
'company': companyid_2001, # => verweist auf periods => companies
'plants': [
{
'id': 'qux',
'product': {
'id': 'Ammoniak',
'process': {
'id': 'SMR+HB',
'technologies': [
technologyid_2001_first, # => verweist auf periods => technologies
technologyid_2001_second
]
}
}
}
]
}
]
},
{
'id': 'FR',
# 'sub_regions': [],
'sites': [
{
'id': 'first_site_in_france',
'company': companyid_2001, # => verweist auf periods => companies
'plants': [
{
'id': 'qux',
'product': {
'id': 'Ammoniak',
'process': {
'id': 'SMR+HB',
'technologies': [
technologyid_2001_first, # => verweist auf periods => technologies
technologyid_2001_second
]
}
}
}
]
}
]
}
],
'companies': [
{
'id': companyid_2001,
'name': 'international_company'
}
],
'technologies': [
{
'id': technologyid_2001_first,
'name': 'SMR',
'specific_cost_per_year': 123,
'specific_energy_consumptions': [
{
'energy_carrier': energy_carrierid_2001_first,
'specific_consumption': 5555
}, # => verweist auf periods => energy_carriers
{
'energy_carrier': energy_carrierid_2001_second,
'energy_consumption': 2333
}
]
},
{
'id': technologyid_2001_second,
'name': 'HB',
'specific_cost_per_year': 1234,
'specific_energy_consumptions': [
{
'energy_carrier': energy_carrierid_2001_first,
'specific_consumption': 555
}, # => verweist auf periods => energy_carriers
{
'energy_carrier': energy_carrierid_2001_second,
'energy_consumption': 233
}
]
}
],
'energy_carrieriers': [
{
'id': energy_carrierid_2001_first,
'name': 'oil',
'group': 'fuel'
},
{
'id': energy_carrierid_2001_second,
'name': 'gas',
'group': 'fuel'
},
{
'id': uniqueid(),
'name': 'conventional',
'group': 'electricity'
},
{
'id': uniqueid(),
'name': 'green',
'group': 'electricity'
}
],
'networks': [
{
'id': uniqueid(),
'name': 'gas',
'sub_networks': [],
'pipelines': [
]
},
{
'id': uniqueid(),
'name': 'gas',
'sub_networks': [],
'pipelines': [
]
}
]
}
]
r.table('periods') \
.insert(periods) \
.run()
Related:
RethinkDB: RqlRuntimeError: Cannot perform bracket on a sequence of sequences
Nested concat_map in combination with r.row operator and bracket drill down does the trick:
r.table('periods') \
.concat_map(r.row['regions']) \
.concat_map(r.row['sites']) \
.concat_map(r.row['plants'])['product']['process'] \
.concat_map(r.row['technologies']) \
.run()

Flutter/Dart group list by date

I have following list of maps,
[
{
"FullName":"Harry Potter",
"DateOfBirth": "2020/02/16",
"Department":"Branch Operation",
"BirthDay":"Friday"
},
{
"FullName":"John Wick",
"DateOfBirth": "2020/02/16",
"Department":"Finance",
"BirthDay":"Friday"
},
{
"FullName":"Solomon Kane",
"DateOfBirth":2020/02/19,
"Department":"Loan",
"BirthDay":"Monday"
}
]
I would like to manipulate above data such that data are grouped by their DateOfBirth, so that result would look like this.
[
{
"DateOfBirth": "2020/02/16",
"BirthDay": "Friday",
"Data":[
{
"FullName": "Harry Potter",
"Department":"Branch Operation",
},
{
"FullName":"John Wick",
"Department":"Finance",
}
]
},
{
"DateOfBirth": "2020/02/19",
"BirthDay": "Monday",
"Data":[
{
"FullName":"Solomon Kane",
"Department":"Loan"
}
]
},
]
In Javascript, this can be achieved by using reduce function and then using Object key mapping.
I also know dart has useful package called collection
As I am new to dart and flutter, I am not sure how to do. Can anybody help me on this?
Thanks
You could use fold and do something like this
const data = [...];
void main() {
final value = data.fold(Map<String, List<dynamic>>(), (Map<String, List<dynamic>> a, b) {
a.putIfAbsent(b['DateOfBirth'], () => []).add(b);
return a;
}).values
.where((l) => l.isNotEmpty)
.map((l) => {
'DateOfBirth': l.first['DateOfBirth'],
'BirthDay': l.first['BirthDay'],
'Data': l.map((e) => {
'Department': e['Department'],
'FullName': e['FullName'],
}).toList()
}).toList();
}
Or like this if you want to use the spread operator, I don't know if its very readable though.
final result = data.fold({}, (a, b) => {
...a,
b['DateOfBirth']: [b, ...?a[b['DateOfBirth']]],
}).values
.where((l) => l.isNotEmpty)
.map((l) => {
'DateOfBirth': l.first['DateOfBirth'],
'BirthDay': l.first['BirthDay'],
'Data': l.map((e) => {
'Department': e['Department'],
'FullName': e['FullName'],
}).toList()
}).toList();

MongoDB push to array with predefined index

How do I add an item to Mongoose, if I want to push it to an item of the array?
I want to push it to the document with predefined _id, to the 'productList' array with predefined 'id', to the 'items' array.
{
"_id" : ObjectId("5ba94316a48a4c828788bcc9"),
"productList" : [
{
"id" : 1,
"items" : [
{
"id" : 1,
"name" : "FLOSS 500",
}
]
}
]
}
I thought that it should be something like this, but it did not work:
Products.findOneAndUpdate({_id: req.body._id, productList: {id: req.body.id}}, {$push: {'items': req.body.product}})
You can try this with positional operator $. For search by nested array property use dot-separated syntax:
Products.findOneAndUpdate({
_id: req.body._id,
'productList.id': req.body.id
}, { $push: { 'productList.$.items': req.body.product } });
Full example:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Products = mongoose.model('Test', new Schema({
productList: []
}));
mongoose.connect("mongodb://localhost:27017/myapp");
let item = new Products({
"_id": mongoose.Types.ObjectId("5ba94316a48a4c828788bcc9"),
"productList": [
{
"id": 1,
"items": [
{
"id": 1,
"name": "FLOSS 500",
}
]
}
]
});
Products.deleteMany({}).then(() => {
return Products.create(item);
}).then(() => {
return Products.findOneAndUpdate({
_id: mongoose.Types.ObjectId("5ba94316a48a4c828788bcc9"),
'productList.id': 1
}, {
$push: {
'productList.$.items': {
"id": 2,
"name": "FLOSS 600",
}
}
});
}).then(() => {
return Products.find({
_id: mongoose.Types.ObjectId("5ba94316a48a4c828788bcc9"),
'productList.id': 1
});
}).then(data => {
console.log(data);
if (data) {
console.log(data[0].productList);
/* [{"id":1,"items":[{"id":1,"name":"FLOSS 500"},{"id":2,"name":"FLOSS 600"}]}] */
}
}).catch(err => {
console.error(err);
});

Change capital letters in mongo to camel casing?

I have a collection named User, which contains the the fields firstName and secondName. But the data is in capital letters.
{
firstName: 'FIDO',
secondName: 'JOHN',
...
}
I wanted to know whether it is possible to make the field to camel case.
{
firstName: 'Fido',
secondName: 'John',
...
}
You can use a helper function to get your desired answer.
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
db.User.find().forEach(function(doc){
db.User.update(
{ "_id": doc._id },
{ "$set": { "firstName": titleCase(doc.firstName) } }
);
});
Run an update operation with aggregate pipeline as follows:
const titleCase = key => ({
$concat: [
{ $toUpper: { $substrCP: [`$${key}`,0,1] } },
{ $toLower: {
$substrCP: [
`$${key}`,
1,
{ $subtract: [ { $strLenCP: `$${key}` }, 1 ] }
]
} }
]
});
db.User.updateMany(
{},
[
{ $set: {
firstName: titleCase('firstName'),
secondName: titleCase('secondName')
} }
]
)
Mongo Playground