Home > Software design >  How to build maps of nested data structures in dart?
How to build maps of nested data structures in dart?

Time:11-11

I want to improve on my current solution of putting values of hierarchical data structures together in a common list of maps. I'm looking for a more concise and more efficient solution, maybe one that does not use a nested for-loop.

Here's the code which includes the problem, a desired output and my current solution:

class Bar{
  String someVal;
  int num;

  Bar(this.someVal, this.num);
}

class Foo{
  String someVal;
  List<Bar> bars;

  Foo(this.someVal, this.bars);
}

void main()
{
  Bar bar1 = Bar("val1", 3);
  Bar bar2 = Bar("val2", 5);
  Bar bar3 = Bar("val3", 2);
  Foo foo1 = Foo("someString1", [bar1, bar2, bar3]);

  Bar bar4 = Bar("val4", 2);
  Bar bar5 = Bar("val5", 3);
  Bar bar6 = Bar("val6", 1);
  Foo foo2 = Foo("someString2", [bar4, bar5, bar6]);

  // Given
  List<Foo> foos = [foo1, foo2];
  
  // Desired result:
  List<Map> namedBars =
  [{"someVal": "someString1", "bar": bar1},
   {"someVal": "someString1", "bar": bar2},
   {"someVal": "someString1", "bar": bar3},
   {"someVal": "someString2", "bar": bar4},
   {"someVal": "someString2", "bar": bar5},
   {"someVal": "someString2", "bar": bar6},
  ];

    // my current solution
    final allBars = foos.map((foo) => foo.bars).expand((bar) => bar).toList();
    var countsBar = foos.map((foo) => foo.bars.length).toList();
    var namedBars = [];
    var k = 0;
    for(var i = 0; i < countsBar.length; i  ){
      for(var j = 0; j < countsBar[i]; j  ){
        namedBars.add({"someVal": foos[i].someVal,
                          "bar": allBars[k]});
        k  ;
      }
    }

CodePudding user response:

Well written question with examples. Good solution by @pskink.

  var pskinkSolution = foos
      .expand((foo) => foo.bars.map((bar) => {
            'someVal': foo.someVal,
            'bar': bar,
          }))
      .toList();

Solution in DartPad:

https://dartpad.dev/?id=a4cade24fded7bf62025daa5879fb373

  • Related