How do I add a new key value to an existing map? I've searched but nowhere seem to answer for my example. My map looks like this:
myMap = {A: {b:3}}
I'm simply trying to add key values into 'A' so it looks like this:
{A: {b:3, c:3}}
Hope that makes sense!
void main() {
var myMap = {'A': {'b':3}};
myMap['A']!['c'] = 3;
print(myMap);
}
Assuming you started with:
var myMap = {'A': {'b': 3}};
You can update like this:
myMap['A'] = {
'b': 3,
'c': 3,
};
Related
I need to generate a query that looks something like:
SELECT v.* FROM versions v
WHERE
(v.id1 = 1 AND v.id2 = 1) OR
(v.id1 = 3 AND v.id2 = 2) OR
(v.id1 = 5 AND v.id2 = 6) OR ...
The parameter to my function contains a list of these paired ids. Unfortunately, id1 and id2 are not the primary keys of this table so I can't use .whereIdsIn().
I am aware of the Brackets object but can't for the life of me figure out how to create a dynamic number of them.
Since you put a generic query, I'll try to answer this generally. You can do something like this:
async foo(tupleList: [number, number][]) {
const builder = createQueryBuilder(Version, 'v');
for (const tuple of tupleList) {
builder.orWhere(new Brackets(qb => {
qb.where("v.id1 = :id1", { id1: tuple[0] })
.andWhere("v.id2 = :id2", { id2: tuple[1] })
}));
}
const result = await builder.getMany();
}
I have created this class
class Opacity {
String a,b,c;
Opacity({this.a, this.b,this.c});
}
And I'm trying to dynamically create an instance of this class only using strings and an hashmap for arguments.
String type = "Opacity";
List<String> args = {'a': 'a', 'b': 'b','c': 'c'}
And I have one constraint, I can't modify the Opacity class.
For creating the instance I thought about using reflection to dynamically create the class from string but I can't figure out how to pass the arguments dynamically.
For passing arguments dynamically to the constructor you can use newInstance method of ClassMirror.
For example
MirrorSystem mirrors = currentMirrorSystem();
ClassMirror classMirror = mirrors.findLibrary(Symbol.empty).declarations[new Symbol('Opacity')];
print(classMirror);
var arguments = {'a': 'a', 'b': 'b', 'c': 'c'}.map((key, value) {
return MapEntry(Symbol(key), value);
});
var op = classMirror.newInstance(Symbol.empty, [], arguments);
Opacity opacity = op.reflectee;
print("opacity.a: ${opacity.a}");
print("opacity.b: ${opacity.b}");
print("opacity.c: ${opacity.c}");
Going from a string to a source name, and further to the thing denoted by that source name, is reflection. It's only available through the dart:mirrors library, or if you generate code ahead-of-time, perhaps using package:reflectable.
This is a point where Dart differs from a language like JavaScript, where you can inspect all values at run-time.
Without reflection, the only way you can call a constructor is if you have actual code performing that call in your code. That would mean that you have to have code like Opacity(a: ..., b: ..., c: ...) at least in one place in your code.
You could define a function like:
Opacity createOpacity(Map<String, String> args) =>
Opacity(a: args["a"], b: args["b"], c: args["c"]);
Then you could perhaps register it by name as:
Map<String, Function> factories = {"Opacity": createOpacity};
and finally use it as:
var type = "Opacity";
var args = {'a': 'a', 'b': 'b', 'c': 'c'};
Opacity myOpacity = factories[type](args);
Is it possible to initialize a list on one line in Dart? Something like the following...
List<int> options = new List<int>{ 1,2,5,9 };
(this is possible in c# and is called a collection initializer)
Yes:
List<int> options = [1, 2, 5, 9];
I'd recommend reading:
https://api.dartlang.org/stable/1.24.3/dart-core/List-class.html
Yes, you can do it using the List.unmodifiable constructor:
var options = new List.unmodifiable([3,6,7,8]);
Or by using the List.from constructor:
var options = new List.from([3,6,7,8]);
Or just like this:
var options = [5,7,9,0];
There are also available List.filled and List.generate factory constructors:
List<int?> s = List.filled(5, 10, growable: true); // [10, 10, 10, 10, 10]
This creates list of length 5, of type int or null, and initializes each element with 10. This list is growable, which means its length can be changed with a setter:
s.length = 10;
s[8] = 2; // [10, 10, 10, 10, 10, null, null, null, 2, null]
After changing the list length, new elements will be initialized with null. If the list element type is not-nullable this will cause Exception.
List.generate generates a list of values.
var n = List.generate(5, (index) => 0); // [0, 0, 0, 0, 0]
The created list is fixed-length, and each element is set to 0.
List<int?> n = List.generate(5, (index) => index * index, growable: true); // // [0, 1, 4, 9, 16]
If we want to create growable list (i.e. we set growable to true) we need to explicitly choose non-nullable type eg. int? as we did here, otherwise increasing list length will raise exception. This stands for both List.generate and List.filled factories.
Good reads about those are:
https://api.dart.dev/stable/1.24.3/dart-core/List/List.generate.html
and
https://api.dart.dev/stable/1.24.3/dart-core/List/List.filled.html
var vals = <int>[1, 2, 3];
var vals2 = List<int>()..addAll([1, 2, 3]);
var vals3 = List<int>.of([1, 2, 3]);
Note that when we don't provide a type, we in fact create a list of a
dynamic type. Also, the new keyword is optional.
Square brackets define a List
var listOfInt = [1,2,3]
Curly brackets define a Set
var setOfInt = {1,2,3};
Curly brackets with colons define a Map
var mapOfIntString = {1: "a", 2: "b"};
It is possible to specify the type explicitly.
var list = <int>[1,2,3]
var setOfInt = <int>{1,2,3};`
var map = <int,String>{1: "a", 2: "b"};
Initialize empty list
List<int> options = [];
Initialize filled list
List<int> options = [1,2,5,9];
I have this map:
var temp= {
'A' : 3,
'B' : 1,
'C' : 2
};
How to sort the values of the map (descending). I know, I can use temp.values.toList()..sort().
But I want to sort in context of the keys like this:
var temp= {
'B' : 1,
'C' : 2
'A' : 3,
};
This example uses a custom compare function which makes sort() sort the keys by value. Then the keys and values are inserted into a LinkedHashMap because this kind of map guarantees to preserve the order.
Basically the same as https://stackoverflow.com/a/29629447/217408 but customized to your use case.
import 'dart:collection';
void main() {
var temp= {
'A' : 3,
'B' : 1,
'C' : 2
};
var sortedKeys = temp.keys.toList(growable:false)
..sort((k1, k2) => temp[k1].compareTo(temp[k2]));
LinkedHashMap sortedMap = new LinkedHashMap
.fromIterable(sortedKeys, key: (k) => k, value: (k) => temp[k]);
print(sortedMap);
}
Try it on DartPad
The SplayTreeMap has a named constructor which accepts map and a comparator which is used to sort given map while building new map. Since SplayTreeMap is a descendant of Map you can easily substitute it.
import 'dart:collection';
void main() {
var unsorted = {'A': 3, 'B': 1, 'C': 2};
final sorted = SplayTreeMap.from(
unsorted, (key1, key2) => unsorted[key1].compareTo(unsorted[key2]));
print(sorted);
}
final Map<String, ClassCategory> category;
...
Map<String, ClassCategory> sorted = SplayTreeMap.from(category,
(key1, key2) => category[key1]!.title.compareTo(category[key2]!.title));
for (var item in sorted.entries) {
...
}
Lets say i have the following JSON
{
names: ["John", "Peter", "Ron", "John", "James", "John"]
}
I need DustJS to render the following names
John
Peter
Ron
James
Notice that these are unique values in an array. Any ideas? Thank you so much!
This can be done using a common algorithm to 'unique' an array:
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
It's done by taking the values, attempting to add them as keys to an object (which will only work if they're different). If success, it adds that key to an array. If fail, it ignores the key. It then returns the array. I have a working dust.js demo here:
Working Demo
I believe this will generate your "also acceptable" form:
{#options}] {.} {#variants} {.options[$idx]} {/variants} {/options}