Ask Your Question
0

How can I filter JSON data in Flutter based on a condition specified in another set of data?

asked 2023-06-20 05:11:09 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-20 05:39:02 +0000

qstack gravatar image

You can use the where method on a list of JSON data to filter based on a condition specified in another set of data. Here is an example:

import 'dart:convert';

void main() {
  // JSON data to filter
  final jsonData = '[{"name": "John", "age": 25}, {"name": "Jane", "age": 30}, {"name": "Bob", "age": 20}]';

  // Condition to filter by
  final agesToKeep = [20, 25];

  // Convert JSON data to a list of maps
  final List<Map<String, dynamic>> data = List<Map<String, dynamic>>.from(json.decode(jsonData));

  // Filter the data based on the agesToKeep condition
  final filteredData = data.where((person) => agesToKeep.contains(person['age'])).toList();

  print(filteredData); // [{"name": "John", "age": 25}, {"name": "Bob", "age": 20}]
}

In this example, we convert the JSON data to a list of maps using json.decode. Then, we use the where method to filter the data based on the agesToKeep condition. Finally, we convert the filtered data back to a list using toList.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-20 05:11:09 +0000

Seen: 10 times

Last updated: Jun 20 '23