Home > Software design >  Extracting values from keys inside multiple key-value pair arrays with dart/flutter
Extracting values from keys inside multiple key-value pair arrays with dart/flutter

Time:05-19

Below I have a simple array that contains key-value pairs. Here's what I'm trying to achieve:

If 'global' == true, print the value of the 'title' key inside that same object. If 'global' == false, do nothing.

So for the example below, we would only print 'hello'.

Any help is greatly appreciated!

void main() {

var messages = [
  {
    'id': 1,
    'title': "hello",
    'global': true,
  }, 
  {
    'id': 2,
    'title': "bye",
    'global': false,
  }, 
];

CodePudding user response:

You could simply iterate into messages:

  var messages = [
    {
      'id': 1,
      'title': "hello",
      'global': true,
    },
    {
      'id': 2,
      'title': "bye",
      'global': false,
    },
    {
      'id': 3,
      'title': "hi",
      'global': true,
    },
  ];

  messages.forEach((element) {
    element["global"] == true ? print(element["title"]) : null;
  });

Output:

hello
hi
  • Related