How Can I convert a Map of (Key1=Value1,Key2=Value2) into a Map of (Value1=Valu2) in Apex? - apex

I have Map<String, Object> results = {Id=10001,Value=7777},
I want a map with {10001=7777} type.
This is what I attempted :-
Map<String,String> TraversedResultMap = new Map<String,String>();
for (String s : results.KeySet()) {
TraversedResultMap.put(String.valueOf((String)results.get(s)),String.valueOf((String)results.get(s)));
}
system.debug('###TRAVERSED RESULT'+TraversedResultMap);
But I'm getting o/p as : {10001=10001,7777=7777}

You're not inserting key as a value in your for loop. That's why you're getting same key-value pair.
See below code:
Map<String,String> TraversedResultMap = new Map<String,String>();
for (String s : results.KeySet()) {
// here key: String.valueOf((String)results.get(s))
// and Value: s
TraversedResultMap.put(String.valueOf((String)results.get(s)),s);
}
system.debug('###TRAVERSED RESULT'+TraversedResultMap);

Related

how can I update multiple values in a firestore map using only one write without overwriting the entire map

this code will overwrite the entire map in firestore
Map<String, String> map = {};
for (MapEntry e in someGientMap.entries) {
map[e.key] = e.value;
}
await db.doc('document path').update({
'FirestoreGiantMap': map,
});
and this code will write the document too many times
for (MapEntry e in someGientMap.entries) {
await db.doc('document path').update({
'FirestoreGiantMap.${e.key}: e.value,
});
}
You're almost there. Combing the two techniques leads to:
Map<String, String> map = {};
for (MapEntry e in someGientMap.entries) {
var key = 'FirestoreGiantMap.' + e.key;
map[key] = e.value;
}
await db.doc('document path').update(map);

getting array from object from api and diplay iteratively

I am getting an array of object json encoded from an api and i would like to display an the each row of objects on a new line
var me3 = jsondata["message"];
for (var i = 1; i < me3.length; i++)
me3.forEach((element) => print(element));
Set<String> set = Set.from(me3);
set.forEach((element) => premiumList
..add(Property(propertyName:"Company : $element[1]", propertyLocation:"SSN : 3001245" )));
The aim is to display each record on a new property sheet and display the the tradename value in each row ..
Using StringBuffer we print
var responseFromAPI = ["test1", "test2", "test3", "test4"];
String _errorMessage = "";
StringBuffer sb = new StringBuffer();
for (String line in responseFromAPI) {
sb.write(line + "\n");
}
_errorMessage = sb.toString();
print(_errorMessage);

How to Adding New Data into JSON Dart?

I have a JSON having some data as an array , and I wanna add
new data to JSON
This is My JSON structure
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID"
}
]```
I want to add new data so it can be like this
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID",
"flag":1
}
]```
Is it possible ? If it is can anyone tell me how to do that ? Thanks in advance.
And this is what I've been doing so far..
List data = json.decode(response.body);
for (int i = 0; i < data.length; i++) {
data.add(data[i]["flag"]=1);
print("object : " + data[i].toString());
}
});
It was printed like I want it, but return error in add line
The error said NoSuchMethodError: Class 'String' has no instance method '[]='
First of all, you have to Decode the JSON
var data=json.decode("Your JSON")
Now this is available as a list and map so you can add fields like
data[key]=value;
after that, you have to Encode it using json.encode
var data1=json.encode(data);
`
It's a good idea to get the JSON formatted and mapped to a Model. This will not only help to do null checks but also increase the readability of your code.
You can use a simple Model like
class myModel {
String id;
String originTime;
String location;
int flag;
myModel({this.id, this.originTime, this.location, this.flag});
myModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
originTime = json['origin_time'];
location = json['location'];
flag = json['flag'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['origin_time'] = this.originTime;
data['location'] = this.location;
data['flag'] = this.flag;
return data;
}
}

Nested Map operation in Dart

I have a Maps of type
Map<String,Map<String,bool>> outerMap;
Map<String,bool> innerMap_1 ,innerMap_2;
I need to nest innerMaps inside outerMap.
innerMap_1 = { 'time_1':true , 'time_2':false };
innerMap_1 = { 'time_3':false ,'time_4':true };
outerMap = { 'date_1':innerMap_1 , 'date_2':innerMap2 };
I need to store outerMap as a string on the Sqlite Database. When I try
jsonEncode(outerMap);
There is an error because it is nested.
How to effectively convert the outerMap to String and then convert that string back to Map ?
outerMap = { 'date_1':innerMap_1 , 'date_2':innerMap2 };
The thing is that you had a spelling error and therefore there was an error. But in my solution I fixed that.
Another thing to notice is that in order to use the jsonEncode function you have to import the dart:convert package.
import 'dart:convert';
void main() {
Map<String, Map<String, bool>> outerMap;
Map<String, bool> innerMap_1, innerMap_2;
innerMap_1 = {'time_1': true, 'time_2': false};
innerMap_2 = {'time_3': false, 'time_4': true};
outerMap = {'date_1': innerMap_1, 'date_2': innerMap_2};
String json = jsonEncode(outerMap);
print(json);
print(jsonDecode(json));
}
You can test your dart code on dartpad.dev.

Ignore a Key with JSON encode

How can I ignore a key when using json.encode?
Something like this:
final map = json.decode(json.encode(routine), reviver: (key, value) {
if (key == "id") {
return null;
}
return value;
});
But this way my map has a key id with value null. I want my map to not have the id key.
Any Idea?
You can remove the key.
routine.remove("id");
final map = json.decode(json.encode(routine));