I am Beginner in flutter, learning map concept. I am confusing map methods. How to delete a specific value from a map?
for example:
Map data = {
"studet1": {"name": "ajk", "age": "22", "place": "delhi"},
"studet2": {"name": "akmal", "age": "25", "place": "up"}
};
I want to delete the "name" from "student1".
data is a nested map, which means that it has another map within the key of student1.
You can use the .remove method to remove a key within a map:
Removes key and its associated value, if present, from the map.
void main() {
Map data ={
"student1":{
"name" : "ajk",
"age":"22",
"place":"delhi"
},
"student2":{
"name" : "akmal",
"age":"25",
"place":"up"
}
};
data['student1'].remove('name');
print(data);
}
Prints:
{student1: {age: 22, place: delhi}, student2: {name: akmal, age: 25, place: up}}
If you want to remove only student1 name
Just use data['student1'].remove('name');
Or if you want to remove all students name use the bleow method
Map data = {
"studet1": {"name": "ajk", "age": "22", "place": "delhi"},
"studet2": {"name": "akmal", "age": "25", "place": "up"}
};
for (int i = 0; i <= data.length - 1; i++) {
data[data.keys.elementAt(i)].remove('name');
}
The output will be
{student1: {age: 22, place: delhi}, student2: {age: 25, place: up}}
Related
My goal is to insert a map key as an id inside map value (which is also a map, the nested one).
Say I have a map as follows
Map<String, dynamic> userMap = {
"id_1" : {
"name": "John",
"surname": "Doe",
"age": 25,
},
"id_2" : {
"name": "Jeremy",
"surname": "Smith",
"age": 42,
}
};
I want to convert this to
Map<String, dynamic> userMap = {
"id_1" : {
"id": "id_1",
"name": "John",
"surname": "Doe",
"age": 25,
},
"id_2" : {
"id": "id_2",
"name": "Jeremy",
"surname": "Smith",
"age": 42,
}
};
I tried this
userMap.entries.map((entry) => (entry.value as Map).putIfAbsent('id', () => entry.key));
but it is not working. Instead it is giving result as (id_1, id_2). What I am doing wrong ?? Is there any way to achieve the desired one ??
userMap.entries.map((entry) => (entry.value as Map).putIfAbsent('id', () => entry.key));
The reason why that doesn't work is because you don't do anything with the result of calling .map(). From the Iterable.map documentation:
Returns a new lazy Iterable.... As long as the returned Iterable is not iterated over, the supplied function f will not be invoked.
Your callback function thus is never called and will not mutate the original Map. You could forcibly iterate over the result of .map() (e.g. userMap.entries.map(...).toList()) to get your desired result. However that's wasteful and misuses Iterable.map.
Iterable.map is meant to be used to perform a functional transformation on an Iterable; you should not use it when the callback has side effects. (A "side effect" is something that the callback does other than just returning a value.) For callbacks where you care about side effects, either use Iterable.forEach or use a normal for loop.
You can use this:
userMap.forEach((k,v) => {(v as Map).putIfAbsent('id', () => k)});
I have a JSON response from my API call. The format is like this.
[
{
"hotelname": "A",
"roomno": "101",
"occupancy": "4"
},
{
"hotelname": "A",
"roomno": "102",
"occupancy": "3"
},
{
"hotelname": "B",
"roomno": "101",
"occupancy": "4"
},
{
"hotelname": "B",
"roomno": "202",
"occupancy": "3"
}
]
I want to write a code where in one dropdown list displays the names of the hotels(A,B,C etc) the other dropdown should display the corresponding roomno.
To achieve this i would like to convert my JSON response to a MAP like the below.
Map<String,String> _hoteldata = {
"101":"A",
"102":"A",
"101":"B",
"202":"B",
};
First, you parse the json using jsonDecode(), then create a map from the list, for example, using Map.fromEntries():
import 'dart:convert';
var rooms = jsonDecode(json) as List;
var hotelData = Map.fromEntries(
rooms.map((room) => MapEntry(room['roomno'], room['hotelname']))
);
I was wondering how I could print just the names only or various if possible. At this point I have a simple for in Loop printing the entire collection.
var players: [[String: Any]] = [
["Name": "Joe Smith",
"Height": 42,
"Experience": true,
"Guardians": "Jime and Jan Smith",
"Team": ""],
["Name": "Jill Tanner",
"Height": 36,
"Experience": true,
"Guardians": "Clara Tanner",
"Team": ""],
["Name": "Bill Bon",
"Height": 43,
"Experience": true,
"Guardians": "Sara and Jenny Bon",
"Team": ""],
]
for teamSelector in players {
print(players)
}
Swift 3
For print the values:
players.values.forEach { (value) in
print(value)
}
For print the "name" (that called 'keys'):
players.keys.forEach { (key) in
print(key)
}
In other style you can write it like:
for key in players.keys{
print("The key is: \(key)")
print("The value is: \(players[key])")
}
You can do the following using your example, but updated to get the name:
for teamSelector in players {
print(teamSelector["Name"])
}
You can also use map to print all the names:
print(players.map { $0["Name"] })
Another option is to loop over each of the players and cast the name as a string and then display the name. Using flatMap here ensures all names are strings.
for name in players.flatMap({ $0["Name"] as? String }) {
print(name)
}
this would print only the names:
players.foreach() { print($0["Name"])
I am creating app that can filter data dynamically.
If i select "John", "US", and leave the sex as blank it will return no result because the query will search a sex that is blank. I can't figure out how can i dynamically filter that in the mongodb.
ex:
var fName="John",
fCountry="US",
fSex="";
db.users.find({ $and[ {sex: fSex}, {first_name: fName}, {country: fCountry} ]})
That query will return none.
I want the code to return a answer like this if i select "John", "US":
{"_id": <object>, "first_name": "John", "sex": "Male", "country": "US"}
users:
{"_id": <object>, "first_name": "John", "sex": "Male", "country": "US"},
{"_id": <object>, "first_name": "Rex", "sex": "Male", "country": "Mexico"},
{"_id": <object>, "first_name": "Jane", "sex": "Female", "country": "Canada"}
Thank You in advance!, btw i am new to mongo
Edited
You can build the query object instead of assuming it's going to looks like a specific structure.
You can add whatever checks you'd like.
var fName="John",
fCountry="US",
fSex="";
var query = { $and: [] };
if (fName !== "") { query.$and.push({name: fName}); }
if (fCountry !== "") { query.$and.push({country: fCountry}); }
if (fSex !== "") { query.$and.push({sex: fSex}); }
db.users.find(query);
Update:
As per #semicolon's comment, the $and here is unnecessary as mongo, by default, will "and" different fields together. A simpler solution reads:
var query = {};
...
query.name = fName; // et cetera.
I'll add that it may become necessary to use the key $and and other operators when building more elaborate queries.
As the title says, I need to retrieve the names of all the keys in my MongoDB collection, BUT I need them split up based on a key/value pair that each document has. Here's my clunky analogy: If you imagine the original collection is a zoo, I need a new collection that contains all the keys Zebras have, all the keys Lions have, and all the keys Giraffes have. The different animal types share many of the same keys, but those keys are meant to be specific to each type of animal (because the user needs to be able to (for example) search for Zebras taller than 3ft and giraffes shorter than 10ft).
Here's a bit of example code that I ran which worked well - it grabbed all the unique keys in my entire collection and threw them into their own collection:
db.runCommand({
"mapreduce" : "MyZoo",
"map" : function() {
for (var key in this) { emit(key, null); }
},
"reduce" : function(key, stuff) { return null; },
"out": "MyZoo" + "_keys"
})
I'd like a version of this command that would look through the MyZoo collection for animals with "type":"zebra", find all the unique keys, and place them in a new collection (MyZoo_keys) - then do the same thing for "type":"lion" & "type":"giraffe", giving each "type" its own array of keys.
Here's the collection I'm starting with:
{
"name": "Zebra1",
"height": "300",
"weight": "900",
"type": "zebra"
"zebraSpecific1": "somevalue"
},
{
"name": "Lion1",
"height": "325",
"weight": "1200",
"type": "lion",
},
{
"name": "Zebra2",
"height": "500",
"weight": "2100",
"type": "zebra",
"zebraSpecific2": "somevalue"
},
{
"name": "Giraffe",
"height": "4800",
"weight": "2400",
"type": "giraffe"
"giraffeSpecific1": "somevalue",
"giraffeSpecific2": "someothervalue"
}
And here's what I'd like the MyZoo_keys collection to look like:
{
"zebra": [
{
"name": null,
"height": null,
"weight": null,
"type": null,
"zebraSpecific1": null,
"zebraSpecific2": null
}
],
"lion": [
{
"name": null,
"height": null,
"weight": null,
"type": null
}
],
"giraffe": [
{
"name": null,
"height": null,
"weight": null,
"type": null,
"giraffeSpecific1": null,
"giraffeSpecific2": null
}
]
}
That's probably imperfect JSON, but you get the idea...
Thanks!
You can modify your code to dump the results in a more readable and organized format.
The map function:
Emit the type of animal as key, and an array of keys for
each animal(document). Leave out the _id field.
Code:
var map = function(){
var keys = [];
Object.keys(this).forEach(function(k){
if(k != "_id"){
keys.push(k);
}
})
emit(this.type,{"keys":keys});
}
The reduce function:
For each type of animal, consolidate and return the unique keys.
Use an Object(uniqueKeys) to check for duplicates, this increases the running
time even if it occupies some memory. The look up is O(1).
Code:
var reduce = function(key,values){
var uniqueKeys = {};
var result = [];
values.forEach(function(value){
value.keys.forEach(function(k){
if(!uniqueKeys[k]){
uniqueKeys[k] = 1;
result.push(k);
}
})
})
return {"keys":result};
}
Invoking Map-Reduce:
db.collection.mapReduce(map,reduce,{out:"t1"});
Aggregating the result:
db.t1.aggregate([
{$project:{"_id":0,"animal":"$_id","keys":"$value.keys"}}
])
Sample o/p:
{
"animal" : "lion",
"keys" : [
"name",
"height",
"weight",
"type"
]
}
{
"animal" : "zebra",
"keys" : [
"name",
"height",
"weight",
"type",
"zebraSpecific1",
"zebraSpecific2"
]
}
{
"animal" : "giraffe",
"keys" : [
"name",
"height",
"weight",
"type",
"giraffeSpecific1",
"giraffeSpecific2"
]
}