How to perform search for a Map in flutter? - list

I am having a Map list with key and values, for example :
map<String, dynamic> my_List = [{"name": "mike", "age": "20"}, {"name": "william", "age": "23"}].
I tried containsValue, but I don't want to use it.
The result I want to get is when search for "i" then I need to get the result like {"mike" and "william"} and when I search for "2" I need only the result {20 and 23}.

Try something like:
String search = "k";
var matchNames = my_List.where(p => p["name"].contains(search)).map(p => p["name"]);
String result = "";
foreach(var name in matchNames){
result += name;
if(name != matchNames.last){
result += " and ";
}
}

Related

Terraform- How to iterate through a list of maps without making duplicates?

I have a list that contains the names (strings) of the secret scopes that I want to create
Example:
ss-list = ["name1", "name2"]
I have a map that contains 2 objects that are applied to each name in my ss-list.
Example:
keyvault-map = {
kv1 = {
id = "abc",
dns-name = "123"
},
kv2 = {
id = "def",
dns-name = "456"
}
}
So for each item in ss-list I need to pull the 2 items inside the map and append to make 1 list.
The end result list that I desire to be returned is...
[
{
"keyvault-id" = "abc"
"keyvault-uri" = "123"
"name" = "name1"
},
{
"keyvault-id" = "def"
"keyvault-uri" = "456"
"name" = "name2"
}
]
I'm looking for how I can iterate through this list and map and return my desired list (with no duplicates).

How to perform a search in array of object flutter?

I am having a Map list with key and values, for example :
map<String, dynamic> my_List = [{"name": "mike", "age": "20"}, {"name":"william","age": "23"}].
I already tried containsValue but I don't want to use it.
The result i need to get is, when i search for m i need to get [{"name": "mike", "age": "20"}, {"name":"william","age": "23"}] , and when i search 3 i need the result as [{"name":"william","age": "23"}].
You could create a Person or User class as julemand101 has suggested but if You have to work with Map try this:
List<Map<String, dynamic>> search(String input){
return my_List.where((e) => e["name"].contains(input) || e["age"].contains(input)).toList();
}

Dart/Flutter - Compare two List<dynamic> if they have the same value of id

I have two List<dynamic> and I am trying to figure out how I can check if there is a same value in the id field
List list1 = [
{"id": 2, "name": "test1"},
{"id": 3, "name": "test3"}
];
List list2 = [
{"id": 2, "name": "test1"}
];
I tried this but it returns me false
var isMatch = (list1.toSet().intersection(list2.toSet()).length > 0);
You can not compare like that because you can't compare dynamic as Boken said, you need to create a class for your object and implement a basic search , you can convert list2 into a set to make the search less complex (contains function)
void main() {
List list1 = [
MyObject(2,"test"),
MyObject(3,"test1")
];
List list2 = [
MyObject(4,"test")
];
for(int i=0;i<list1.length;i++){
if(list2.contains(list1[i])){
// do your logic
print(true);
break;
}
}
}
class MyObject{
int id;
String name;
MyObject(int id,String name){
this.id = id;
this.name = name;
}
// redifine == operator
bool operator ==(o) => (o as MyObject).id == this.id;
}

customized sorting using search term in django

I am searching a term "john" in a list of dict ,
I have a list of dict like this :
"response": [
{
"name": "Alex T John"
},
{
"name": "Ajo John"
},
{
"name": "John",
}]
I am using :
response_query = sorted(response, key = lambda i: i['name'])
response_query return ascending order of result only but I need a result with first name as a priority.
Expected result:
{
"name": "John"
},
{
"name": "Ajo John"
},
{
"name": "Alex T John",
}
The first name containing search term should appear first.
If you need to sort with priorities you can try a key-function that returns tuple. In your particular case, as far as I got the question, this function will work fine:
response_query = sorted(
response,
key=lambda i: (len(i['name'].split()) > 1, i['name'])
)
In other words, I added the condition len(i['name'].split()) > 1 that return False (it will go first) if the name consists of one word only, else True.
For the case, if you need the priority condition as the name starts with the term you used in the search, the result would be:
term = 'john'
...
response_query = sorted(
response,
key=lambda i: (not i['name'].lower().startswith(term), i['name'])
)

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;
});
}