Reputation: 47
How can I print out only the lname
s 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
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);
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