Access a list item stored in key value pair inside a list of map - list

I am using flutter/dart and I have run into following problem.
I have a list of map like this.
var questions = [
{
'questionText': 'What\'s your favorite color?',
'answer': ['Black', 'Red', 'Green', 'White']
},
{
'questionText': 'What\'s your favorite animal?',
'answer': ['Deer', 'Tiger', 'Lion', 'Bear']
},
{
'questionText': 'What\'s your favorite movie?',
'answer': ['Die Hard', 'Due Date', 'Deep Rising', 'Dead or Alive']
},
];
Now suppose I need to get the string Tiger from this list. How do I do that? Dart is seeing this as List<Map<String, Object>> questions

Maybe a more portable way with a function:
String getAnswer(int question, int answer) {
return (questions[question]['answer'] as List<String>)[answer];
}
// Get 'Tiger'
String a = getAnswer(1, 1);

You can convert object in list in following way and then use index to get any value.
var p = questions[1]['answer'] as List<String>;
print(p[1]);

Related

How can I access a value from a list of maps containing a list in Dart?

I'm attempting to extract a value from list contained in a list of maps, but am
getting the following error: The operator '[]' isn't defined for the type 'Object'
From the following list, I'd like to access a value such as 'Pizza':
List<Map<String,Object>> questions = [
{
'question': 'What is your favorite food',
'answers': [
'Pizza',
'Tacos',
'Sushi',
],
},
];
When I try to print an answer within the list of answers, it doesn't work:
// Does not work
// The operator '[]' isn't defined for the type 'Object'
print(questions[0]['answers'][0]);
I'm able to save the answers list into a variable to of type list then print a specific list item:
// Works
List answerList = questions[0]['answers'];
print(answerList[0]);
Why doesn't the first way work, and how can I get this to work with one command?
Rather than returning an Object return a dynamic as it has an operator []
List<Map<String, dynamic>> questions = [
{
'question': 'What is your favorite food',
'answers': [
'Pizza',
'Tacos',
'Sushi',
],
},
];

Mongodb conditional query search under an array

I have a data where an array is there. Under that array Many array of objects is there. I am mentioning the raw data so that anyone guess the structure
{
_id: ObjectId(dfs45sd54fgds4gsd54gs5),
content: [
{
str: "Hey",
isDelete: false
},
{
str: "world",
isDelete: true
}
]
}
So I want to search any string that match and I have top search under an array.
So my query is like this:
let searchTerm = req.body.key;
db.collection.find(
{
'content.str': {
$regex: `.*\\b${searchTerm}\\b.*`,
$options: 'i',
}
}
)
So this will return the data. Now for some reason I have to search the data if isDelete: false.
Right now it returns the data whether isDelete is true/false because I have not mentioned the conditon.
Can anyone help me out regarding this to get the data through condition. I want this to Mongodb Query only.
Any help is really appreciated.
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria,
db.collection.find({
content: {
$elemMatch: {
isDelete: true,
str: {
$regex: `.*\\b${searchTerm}\\b.*`,
$options: "i"
}
}
}
},
{
"content.$": 1
})
Working Playground: https://mongoplayground.net/p/VkdWMnYtGA3
You can add another condition there as belo
db.test2.find({
$and: [
{
"content.str": {
$regex: "hey",
$options: "i",
}
},
{
"content.isDelete": false
}
]
},
{
'content.$':1 //Projection - to get only matching array element
})

Dart - find duplicate values on a List

how can I find duplicate values on a list,
Let's say I got a List like this:
List<Map<String, dynamic>> users = [
{ "name": 'John', 'age': 18 },
{ "name": 'Jane', 'age': 21 },
{ "name": 'Mary', 'age': 23 },
{ "name": 'Mary', 'age': 27 },
];
How I can iterate the list to know if there are users with the same name?
A simple way would be this:
void main() {
List<Map<String, dynamic>> users = [
{ "name": 'John', 'age': 18 },
{ "name": 'Jane', 'age': 21 },
{ "name": 'Mary', 'age': 23 },
{ "name": 'Mary', 'age': 27 },
];
List names = []; // List();
users.forEach((u){
if (names.contains(u["name"])) print("duplicate ${u["name"]}");
else names.add(u["name"]);
});
}
Result:
duplicate Mary
Probably a cleaner solution with extensions.
By declaring:
extension ListExtensions<E> on List<E> {
List<E> removeAll(Iterable<E> allToRemove) {
if (allToRemove == null) {
return this;
} else {
allToRemove.forEach((element) {
this.remove(element);
});
return this;
}
}
List<E> getDupes() {
List<E> dupes = List.from(this);
dupes.removeAll(this.toSet().toList());
return dupes;
}
}
then you can find your duplicates by calling List.getDupes()
Note that the function removeAll doesn't exist in my current Dart library, in case you're reading this when they implement it somehow.
Also keep in mind the equals() function. In a List<String>, ["Rafa", "rafa"] doesn't contain duplicates.
If you indeed want to achieve this level of refinement, you'd have to apply a distinctBy function:
extension ListExtensions<E> on List<E> {
List<E> removeAll(Iterable<E> allToRemove) {
if (allToRemove == null) {
return this;
} else {
allToRemove.forEach((element) {
this.remove(element);
});
return this;
}
}
List<E> distinctBy(predicate(E selector)) {
HashSet set = HashSet();
List<E> list = [];
toList().forEach((e) {
dynamic key = predicate(e);
if (set.add(key)) {
list.add(e);
}
});
return list;
}
List<E> getDupes({E Function(E) distinctBy}) {
List<E> dupes = List.from(this);
if (distinctBy == null) {
dupes.removeAll(this.toSet().toList());
} else {
dupes.removeAll(this.distinctBy(distinctBy).toSet().toList());
}
return dupes;
}
}
I had a feeling Rafael's answer had code similar to Kotlin so I dug around and saw that these functions are part of the kt_dart library which basically gets the Kotlin standard library and ports it to Dart.
I come from a Kotlin background so I use this package often. If you use it, you can simply make the extension this much shorter:
extension KtListExtensions<T> on KtList<T> {
KtList<T> get duplicates => toMutableList()..removeAll(toSet().toList());
}
just make sure to add kt_dart on your pubspec: kt_dart: ^0.8.0
Example
final list = ['apples', 'oranges', 'bananas', 'apples'].toImmutableList();
final duplicates = list.duplicates; // should be ['apples'] in the form of an ImmutableList<String>
void main() {
List<String> country = [
"Nepal",
"Nepal",
"USA",
"Canada",
"Canada",
"China",
"Russia",
];
List DupCountry = [];
country.forEach((dup){
if(DupCountry.contains(dup)){
print("Duplicate in List= ${dup}");
}
else{
DupCountry.add(dup);
}
});
}

Check if inner lists contain some string value in Flutter

I have searched a lot. But couldn't get what I am looking for.
I have a list with inner lists as its objects
final posts = [ ["My First Post, "myPostId"], ["My SecondPost, "myPostId2"]..... ];
So, I want to check if the list contains the word First.
It is working with 1D lists like
posts = ["My First Post", "My Second Post"];
posts.where((p)=>p.contain("First")....
//gives the correct result
But what's the way to get from the inner lists.
Actual Code
final suggestion = query.isEmpty?courseNameList:courseNameList
.where((test)=>test.contains(query.toLowerCase())).toList();
Thanks in advance!
Hello check this solution if it is ok:
final posts = [
["My First Post", "myPostId"],
["My SecondPost", "myPostId2"],
];
void main() {
List suggestions = List();
posts.forEach((postList){
if(postList[0].contains("First"))
suggestions.add(postList);
});
suggestions.forEach((sugg)=>print("Found ID: ${sugg[1]}"));
}
void main() {
final result = posts.any((e) => e.any((e) => e.contains('First')));
print(result);
}
final posts = [
["My First Post", "myPostId"],
["My SecondPost", "myPostId2"]
];

Lists AS value of a Map in Dart

I want to create a map of members, but every membres have 3 propreties : first name, last name, and username. How can I create like a list of liste, but with a map.
So I want to have something like :
var membres= {['lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'],
['lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'],
};
As you know, this code doesn't work. But it explain pretty well what I am trying to do.
I think you are confusing the two constructs here.
Read this introduction to the language: http://www.dartlang.org/docs/dart-up-and-running/ch02.html#lists
A list is a list of elements which can be denoted with the shorthand [...] syntax:
var list = [1, 2, "foo", 3, new Date.now(), 4];
Whereas a map can be denoted with the curly brace shorthand syntax:
var gifts = { // A map literal
// Keys Values
'first' : 'partridge',
'second' : 'turtledoves',
'fifth' : 'golden rings'
};
So, let's modify your code to work:
var members = [
{
'lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'
},
{
'lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'
}
];
You can, for example, print the information like this:
members.forEach((e) {
print(e['firstname']);
});
If I understand your intent correctly, you want to have a list of maps. What you have is correct except you confused [ and {. The following works:
var membres = [
{'lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'},
{'lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'}
];
As an example, to get a list of all usernames:
print(membres.map((v) => v['username']));
If you don't really need a Map, what about using a class to improve the structure of your code :
class Member {
String firstname;
String lastname;
String username;
Member(this.firstname, this.lastname, this.username);
}
main() {
final members = new List<Member>();
members.add(new Member('Pierre', 'Bonneau', 'mariobross'));
members.add(new Member('Alex', 'Hamel', 'Queenlatifa'));
// use members
}
You mean like this?
// FirstName => LastName => Value
var lookup = new Map<String, Map<String, String>>();
// get / set values like this
void setValue(String firstName, String lastName, String value) {
if (!lookUp.containsKey(firstName))
lookUp[firstName] = new Map<String, String>();
lookUp[firstName][lastName] = value;
}
String getValue(String firstName, String lastName) {
if (!lookUp.containsKey(firstName)) return "";
return lookUp[firstName][lastName];
}
First of all you need to create a map with value as list. Dont forget to initialize it
then if you want to fill it you first need to use built in function like putIfAbsent as in dart to add first object in list and then use update to add items in list. therefore you will need two arrays. First to put elements and then to add elements in list with same key. Also you can use try catch to identify if the key is present or not to do that in one loop
for (var item in days) {
var date_time = DateTime.parse(item["date"] + " 00:00:00");
_events[date_time] = _events.putIfAbsent(
date_time,
() => [
{
"title": item["title"],
"date": item["date"],
"time": reUse.get_time_am_pm_format(item["time"]),
"feature": item["feature"],
}
]);
}
for (var item in days) {
var date_time = DateTime.parse(item["date"] + " 00:00:00");
_events[date_time] = _events.update(date_time, (value) {
value.add({
"title": item["title"],
"date": item["date"],
"time": reUse.get_time_am_pm_format(item["time"]),
"feature": item["feature"],
});
return value;
});
}