user7560011
user7560011

Reputation: 47

How to iterate a particular item on a JSON list in flutter?

How can I print out only the lnames from the JSON list? The code below is an example.

void main() {
  
//   int index = 0;
  
  List sample = [
    {
      'fname': 'sellerA',
      'lname': 'bola',
      'companyName': 'Faithtuts',
      'country': 'Nigeria',
    },
    
    {
      'fname': 'sellerB',
      'lname': 'abbey',
      'companyName': 'Xerox',
      'country': 'Dubai',
    },
    
    {
      'fname': 'sellerC',
      'lname': 'grace',
      'companyName': 'Nebrob',
      'country': 'Japan',
    },
  ];
  
    for(int index = 0; index < sample.length; index++){
      
      var getCName = sample.map((e) => sample[index]['lname']);
      print('$getCName');
  }
}

The Result:

(bola, bola, bola)
(abbey, abbey, abbey)
(grace, grace, grace)

But I am looking to get something like this instead. (bola, abbey, grace)

Upvotes: 0

Views: 741

Answers (1)

Thierry
Thierry

Reputation: 8393

By combining your for loop with map, you are iterating twice on your list.

Instead, try this:

for(int index = 0; index < sample.length; index++) {
  var getCName = sample[index]['lname'];
  print('$getCName');
}

Or:

for(final element in sample) {
  var getCName = element['lname'];
  print(getCName);
}

Or, simply:

sample.map((element) => element['lname']).forEach(print);

Full example

void main() {

  List sample = [
    {
      'fname': 'sellerA',
      'lname': 'bola',
      'companyName': 'Faithtuts',
      'country': 'Nigeria',
    },
    {
      'fname': 'sellerB',
      'lname': 'abbey',
      'companyName': 'Xerox',
      'country': 'Dubai',
    },
    {
      'fname': 'sellerC',
      'lname': 'grace',
      'companyName': 'Nebrob',
      'country': 'Japan',
    },
  ];

  sample.map((element) => element['lname']).forEach(print);

}

This prints the following to the console:

bola
abbey
grace

Upvotes: 1

Related Questions