dart, a nice way of replacing keys and values in maps? -
i have map
, want go through both values
, keys
, replace occurrences of particular objects meet set criteria other objects, if find key meets specific criteria.
want swap key different object still points @ same value object in map, if find value want replace want original key point @ replacement value.
here code works simplified example looks quite ugly, there nicer way of achieving this, meaning method doesn't require extract every key , value want replace , write replacements in.
nicer able iterate of map once rather iterating on keys, , iterating on keys , values replaced?
void main(){ //replace values of instance object , keys starting "t" same key minus "t" var m = { "one": new a(), "two": new a(), "three": new b(), "four": new b() }; mapkeyandvalueswapper(m, keymeetscondition: (k) => k.startswith("t"), valuemeetscondition: (v) => v a, keyreplacer: (k) => k.replacefirst("t", ""), valuereplacer: (v) => new object()); print(m); } mapkeyandvalueswapper(map m, {bool keymeetscondition(key), bool valuemeetscondition(value), dynamic keyreplacer(key), dynamic valuereplacer(value)}){ var keystoreplace = []; var keystoreplacevaluesfor = []; var keys = m.keys; keys.foreach((k){ if(keymeetscondition != null){ if(keymeetscondition(k)){ keystoreplace.add(k); } } if(valuemeetscondition != null){ if(valuemeetscondition(m[k])){ keystoreplacevaluesfor.add(k); } } }); keystoreplacevaluesfor.foreach((k){ m[k] = valuereplacer(m[k]); }); keystoreplace.foreach((k){ m[keyreplacer(k)] = m.remove(k); }); } class a{} class b{}
i think same:
map newmap = {}; m.foreach((k, v) { var key = k; var value = v; if(m[k] a) { value = new object(); } if(k.startswith('t')) { key = k.replacefirst('t', ''); } newmap[key]=value; });
Comments
Post a Comment