Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an object to array (map) in Dart?

How to convert an Object type to a Map type (array) in Dart, so the variables become key/value pairs?

like image 643
Will Squire Avatar asked Dec 10 '14 16:12

Will Squire


1 Answers

/**
   * Uses refection (mirrors) to produce a Map (array) from an object's
   * variables. Making the variable name the key, and it's value the
   * value.
   */
  Map objectToMap(Object object)
  {
    // Mirror the particular instance (rather than the class itself)
    InstanceMirror instanceMirror = reflect(object);
    Map dataMapped = new Map();

    // Mirror the instance's class (type) to get the declarations
    for (var declaration in instanceMirror.type.declarations.values)
    {
      // If declaration is a type of variable, map variable name and value
      if (declaration is VariableMirror)
      {
        String variableName = MirrorSystem.getName(declaration.simpleName);
        String variableValue = instanceMirror.getField(declaration.simpleName).reflectee;

        dataMapped[variableName] = variableValue;
      }
    }

    return dataMapped;
  }
like image 198
Will Squire Avatar answered Nov 03 '22 12:11

Will Squire