How to get a specific map out of a list of maps that has a bigger than or smaller than value than the rest? - arrays

I'm working on a app where I retrieve json data via http, and I have made the listview.builder and all of that. Now I want to make a filter button to show the lists that only have values below a certain integer.
for example:
my list of maps goes something like this
[
{
"name": "jess",
"age": "28",
"job": "doctor"
},
{
"name": "jack",
"age": "30",
"job": "jobless"
},
{
"name": "john",
"age": "24",
"job": "doctor"
},
{
"name": "sara",
"age": "23",
"job": "teacher"
}...etc
]
Now I want to press that filter button and in my listview show only those that are below or above the age of 25.

You can map over it and add your "filter" inside the condition. Since you save age as String you have to parse it to an int:
var filteredList = myMapList.map((e){
int? parsedAge = int.tryParse(e["age"]!);
if(parsedAge != null && parsedAge >= 25){
return e;
}
}).toList();

I got the answer and it was there all the time I just didn't thought about that much.
In case anyone faces the same issue, here's how it worked for me.
list filteredList = peopleDetailsList.where((element) => int.parse(element['age'] < 25).toList();

Related

How to convert json objects to json array in flutter

This is my json response data. I would like to display this data in listview using map but i dont know how to convert the objects of objects to array of data.
{
"success": true,
"data": {
"addresses": {
"abc": {
"address_id": "121",
"firstname": "Demo",
"lastname": "User",
"company": "Demo Company name",
"telephone": "1-541-754-3011",
"address_1": "Demo",
"address_2": "test address",
"postcode": "3333",
"city": "Berlin",
"zone_id": "1256",
"zone": "Berlin",
"zone_code": "BER",
"country_id": "81",
"country": "Germany",
"longitude": "",
"lattitude": "",
"iso_code_2": "DE",
"iso_code_3": "DEU",
"address_format": "{company}\r\n{firstname} {lastname}\r\n{address_1}\r\n{address_2}\r\n{postcode} {city}\r\n{country}",
"custom_field": null
}
}
}
}
I assume you want to display dynamic keys (eg: abc) inside addresses object. For this, you need to iterate through addresses object for keys and values.
//json you provide
addresses = json["data"]["addresses"];
addresses.forEach((final String key, final value) {
//here key will be abc & value will be json object
//you can add key or value to a different list and use for list rendering later
});
You can use JSON to dart tool, which is available online for free.
Paste your JSON to left panel and select dart language from upper right corner,
You will get your dart class code, in which you can use methods like .toMap() and .toJson(),
This can be very helpful for huge JSON data.

Parsing JSON to do math?

I'm new to programming (especially JSON format), so please forgive me not for using proper terminology :)
Using Python 3.7 Requests module, I receive a JSON response. To keep things simple, I made an example:
{
"Bob":
{
"Age": "15",
"LastExamGrade": "45",
},
"Jack":
{
"Age": "16",
"LastExamGrade": "58",
}
}
What I would like to do is parse the JSON responses to extract two items from each response/structure and save it to a list like this (I think this is called a tuple of tuples?):
[("Bob","45"),("Jack","58")]
Then, after receiving doing this, I will receive another similar response, such as the following (where the only thing that changed is the exam grade):
{
"Bob":
{
"Age": "15",
"LastExamGrade": "54",
},
"Jack":
{
"Age": "16",
"LastExamGrade": "70",
}
}
I want to also save the name and grade into a tuple of tuples (list).
Lastly, I would like to subtract the first exam score of each person from their last exam score, and save this into a final list, which includes the name, final exam grade, and grade improvement, like this:
[("Bob","54","9"),("Jack","67","12")]
What is the simplest way to do this using Python 3? As for my own research, I've searched all throughout StackOverflow, but couldn't find out how to parse a JSON like mine (For example, in mine, the name is outside of the curly braces), and had difficulty doing math operations for JSON items.
I'd recommend using a dedicated package for calculations like pandas:
first_exam_grades = pd.DataFrame.from_dict(first_exam_results, orient='index').astype(int)
second_exam_grades = pd.DataFrame.from_dict(second_exam_results, orient='index').astype(int)
improvements = second_exam_grades.LastExamGrade.to_frame()
improvements['Improvement'] = second_exam_grades.LastExamGrade - first_exam_grades.LastExamGrade
This will give you something that looks like this:
Now you can output it anyway you'd like
list(zip(*([improvements.index.tolist()] + [improvements[c].values.tolist() for c in improvements])))
This will give you [('Bob', 54, 9), ('Jack', 70, 12)] as you want.
One possible solution, using coroutines. Coroutine receive_message holds up to last two values LastExamGrade from the message for each student and produces list of student name, last grade and improvement over last grade:
json_messages = [
# 1st message:
{
"Bob":
{
"Age": "15",
"LastExamGrade": "45",
},
"Jack":
{
"Age": "16",
"LastExamGrade": "58",
}
},
# 2nd message
{
"Bob":
{
"Age": "15",
"LastExamGrade": "54",
},
"Jack":
{
"Age": "16",
"LastExamGrade": "70",
}
},
# 3nd message (optional)
{
"Bob":
{
"Age": "15",
"LastExamGrade": "14",
},
"Jack":
{
"Age": "16",
"LastExamGrade": "20",
}
}
]
def receive_message():
d, message = {}, (yield)
while True:
for k, v in message.items():
d.setdefault(k, []).append(v['LastExamGrade'])
d[k] = d[k][-2:] # store max last two messages
message = yield [(k, *tuple(v if len(v)==1 else [v[1], str(int(v[1])-int(v[0]))])) for k, v in d.items()]
receiver = receive_message()
next(receiver) # prime coroutine
for msg in json_messages:
print(receiver.send(msg))
Prints:
[('Bob', '45'), ('Jack', '58')]
[('Bob', '54', '9'), ('Jack', '70', '12')]
[('Bob', '14', '-40'), ('Jack', '20', '-50')]

Import data - with firebase keys

I am trying to import some data into firebase
{
"people":
[
{
"name": "John Smith",
"age": 23,
},
{
"name": "Tony Jones",
"age": 61,
},
]
}
This is fine but it adds a "traditional" array index in firebase (0,1) - which I believe is bad?
When I insert a new value via my web form I get a mix
"0" : {
"name": "John Smith",
"age": 23,
},
"1" : {
"name": "Tony Jones",
"age": 61,
},
"-LgWkhX2DdD_ChbWJkXo" : { // inserted via form it has a firebase index
"name": "Simon Green",
"age": 37,
}
How can I get the initial inserted data to use firebase indexes it is just a normal .json file.
{
"people":
[
{
"name": "John Smith",
"age": 23,
},
{
"name": "Tony Jones",
"age": 61,
},
]
}
When you write array type JSON data into Realtime Database, you are going to get array type numeric indexes in the database. If you don't want to write like this, you will have to convert the array yourself - there is no API that's going to do that for you. You'll have to read the JSON, iterate each element of the array, and write each item into the database the way you want it to be written. It looks like perhaps you want to add each item using an automatic push ID, since you are trying to create something that looks like "-LgWkhX2DdD_ChbWJkXo".

Angular2,Typescript:How to push array of objects into another array of objects with only a few fields of the object

I know how to operate on array of objects but never had the necessity to push one array data into another. I need to push an array of objects into another array with only 2 fields of the object. Right now my object format is somewhat like this
data: [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
I want to push this into another array but I want only courseid and name in the object. I've read that we need to initialise the object in the constructor, use slice() and a few other functions and then push but I don't know how can I do it for mine since I need to push one array data into another.Kindly someone help me in this regard.
You're looking for the array map() method:
const newArray = array.map(o => {
return { name: o.name, courseid: o.courseid };
});
Try this:
let data = [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
let other = []; // your other array...
data.map(item => {
return {
courseid: item.courseid,
name: item.name
}
}).forEach(item => other.push(item));
console.log(JSON.stringify(other))
// => [{"courseid":"1","name":"Btech"},{"courseid":"2","name":"BCom"}]
You can simply do it like this.
//assign your array of object to variable
var youArray:Array<any>= [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
var resultArray:Array<any>=[] //empty array which we are going to push our selected items, always define types
youArray.forEach(i=>{
resultArray.push(
{
"name":i.name,
"courseid":i.courseid
});
});
console.log(resultArray)
if you still have doubts about this.please follow this url
Map to a returning JSON data, subscribe it to an existing array or an empty one. #typescript
let pictimeline= [];
var timeline = this.picService.fetchtimeline(this.limit)
.map((data : Response) => data.json())
.subscribe(pictimeline=> this.pictimeline = pictimeline);
console.log(this.pictimeline);

Node.JS - How to access Values of Dictionary within an Array of a Key in a Dictionary?

I'm new in Node.JS and I'm able to parse the JSON data and do a console log to print out name and badges.
var details = JSON.parse(body);
console.log(details.name, details.badges.length);
But I don't know how I can get the data inside the arrays of the bagdes such as id, name, url.
I tried
console.log(details.badges.length.id);
But nothing shows up. How can I access that? Thank you.
{
"name": "Andrew Chalkley",
"badges": [
{
"id": 49,
"name": "Newbie",
"url": "http:\/\/teamtreehouse.com\/chalkers",
"icon_url": "https:\/\/achievement-images.teamtreehouse.com\/Generic_Newbie.png",
"earned_date": "2012-07-23T19:59:34.000Z",
"courses": [
]
},
{
"id": 26,
"name": "Introduction",
"url": "http:\/\/teamtreehouse.com\/library\/html\/introduction",
"icon_url": "https:\/\/achievement-images.teamtreehouse.com\/HTML_Basics.png",
"earned_date": "2012-07-23T21:57:24.000Z",
"courses": [
{
"title": "HTML",
"url": "http:\/\/teamtreehouse.com\/library\/html",
"badge_count": 1
},
{
"title": "Introduction",
"url": "http:\/\/teamtreehouse.com\/library\/html\/introduction",
"badge_count": 1
}
]
}
}
It is an array, so you need the index, for example: details.badges[0].id
This will return the first (index 0) element id.
.length only returns the length of the array, so it will not be useful to get the data in it.

Resources