Home > Software engineering >  How to get another key value from an array of json?
How to get another key value from an array of json?

Time:07-22

Lets say I have these arrayed JSON values

[{operation_id: 2, operation_name: FAITHFUL BELIEVERS}, 
{operation_id: 3, operation_name: SAMPLE OP}, 
{operation_id: 4, operation_name: SAMPLE OP 2}]

Now I will select the operation name 'SAMPLE OP' but I want to display the value of its operation_id. How would I do that?

CodePudding user response:

Your JSON is a list of maps, so use where on the list to filter it by your predicate. Better still, use firstWhere as we assume there's just one match.

The match function returns true if the operation name member of the map matches.

firstWhere returns the first matching map, and you want the operation id member of that map.

  final id = list
      .firstWhere((m) => m['operation_name'] == 'SAMPLE OP')['operation_id'];
  • Related