0

I have json data but i need to convert the json to Map in dart/flutter. The json data is :

{"kabupaten": [
        {
            "jec_kabupaten_id": "71",
            "jec_propinsi_id": "8",
            "name": "Aceh Barat"
        },
        {
            "jec_kabupaten_id": "76",
            "jec_propinsi_id": "8",
            "name": "Aceh Barat Daya"
        }, 
        {
            "jec_kabupaten_id": "91",
            "jec_propinsi_id": "9",
            "name": "Medan"
        }, 
         {
            "jec_kabupaten_id": "92",
            "jec_propinsi_id": "9",
            "name": "Sinabung"
        }
    ]}

I want to convert to this Map with dart/flutter:

 {
   "8":{
      "71":"Aceh Barat",
      "76":"Aceh Barat Daya",
      "68":"Aceh Besar"
   },
   "9":{
      "91":"Medan",
      "92":"Sinabung"
   }
}
2

1 Answer 1

2

It is possible to transform the data using fold for example.

void main() {
  const data = {
    "kabupaten": [
      {
        "jec_kabupaten_id": "71",
        "jec_propinsi_id": "8",
        "name": "Aceh Barat",
      },
      {
        "jec_kabupaten_id": "76",
        "jec_propinsi_id": "8",
        "name": "Aceh Barat Daya",
      },
      {
        "jec_kabupaten_id": "91",
        "jec_propinsi_id": "9",
        "name": "Medan",
      },
      {
        "jec_kabupaten_id": "92",
        "jec_propinsi_id": "9",
        "name": "Sinabung",
      },
    ],
  };

  final result = data['kabupaten']?.fold<Map<String, Map<String, String>>>(
    {},
    (prev, elem) => prev
      ..[elem['jec_propinsi_id']!] ??= {}
      ..[elem['jec_propinsi_id']!]![elem['jec_kabupaten_id']!] = elem['name']!,
  );

  print(result);
}

An alternative would be to build up the result in a for loop:

final result = <String, Map<String, String>>{};
for (final elem in data['kabupaten'] ?? []) {
  result[elem['jec_propinsi_id']!] ??= {};
  result[elem['jec_propinsi_id']!]![elem['jec_kabupaten_id']!] = elem['name']!;
}
Sign up to request clarification or add additional context in comments.

1 Comment

It works! Thank you so much for the help @mmcdon20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.