How to match id with current id in array - flutter

How I will check current user id == id and show user like or not in UI
"reference":[
{
"id":"123",
"userid"234"
},
{
"id":"1423",
"userid"25534"
},
{
"id":"15423",
"userid"2335534"
},
]

if this is json response try to convert it in models using https://javiercbk.github.io/json_to_dart/
or here is code that can work for u
var reference = [
{"id": "123", "userid": "234"},
{"id": "1423", "userid": "25534"},
{"id": "15423", "userid": "2335534"},
];
var r = reference.firstWhere((e) => e["id"] == "123");
print(r);
// output
{id: 123, userid: 234}

Related

How to reference two different collections of same db based on object_id in mongo and fastapi

my schema for two collections.
class SectionModel(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
name: str = Field(max_length=50)
class Config:
allow_population_by_field_name = True
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}
schema_extra = {
"example": {
"name": "",
}
}
class FaqModel(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
section_id:str
question:str = Field(max_length=50)
answer:str = Field(max_length=100)
class Config:
allow_population_by_field_name = True
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}
schema_extra = {
"example": {
"section_id": "",
"question": "",
"answer": "",
}
}
my endpoint to create/add data
#router.post("/section",tags=["FAQ"])
def create_section(data: SectionModel = Body(...)):
try:
data = jsonable_encoder(data)
new_section = crud.create_section(data=data)
return {"success":True}
my crud method
def create_section(data):
data = db["sections"].insert_one(data)
return data
my db looks like this after adding data
db.sections.find().pretty();
[
{
_id: '63e4a4d9304637ec1b578136',
name: 'karnataka'
},
{
_id: '63e4c2056f1845a3fc2180c5',
name: 'Cricket'
}
]
db.faqs.find().pretty();
[
{
_id: '63e4cd7a1fdf5ee828bb33b9',
section_id: '63e4a4d9304637ec1b578136',
question: 'how many districts are in karnataka',
answer: '31'
},
{
_id: '63e4cd7a1fef5ee828c2b83b7',
section_id: '63e4c2056f1845a3fc2180c5',
question: 'who is called as hitman',
answer: 'Rohit sharma'
}
]
in faqs collection i am storing section_id as string and not referenced anywhere. if it is correct way then how to fetch response like,
{
"section": ["karnataka", "Cricket"],
"faq": {
"karnataka": [{
"question": "how many districts are in karnataka",
"answer": "31"
}, {
"question": "q2",
"answer": "ans2"
}],
"Cricket": [{
"question": "who is called as hitman",
"answer": "rohit sharma"
}, {
"question": "q4",
"answer": "ans4"
}]
}
}
if not this way means how to reference from the model and achieve this.
Thanks for input.

Search Key in Nested json in Dart/Flutter

I want to search the key "AylaHeartBeatFrequency" inside nested json. how to search and get its value ? in flutter/dart
{
"sAWSIoT": {
"CloudStatus": 1,
"PairingFlag": 0,
},
"sDebug": {
"LocalDebugMsg_d": "Model ID",
"AylaHeartBeatFrequency": 0
},
"Product": {
"Mode": 1,
"Model": "abc"
},
"data": {
"DeviceType": 300,
"Endpoint": 0,
"UniID": "0000000000000000"
}
}
You can do:
var map = /*put your json here. You can use json.decode() on the json if it's not yet formatted*/, value;
for(var item in map.values) {
if(item.containsKey('AylaHeartBeatFrequency') value = item['AylaHeartBeatFrequency']) ;
}

dart flutter max value from list of objects

Looking for some help how to select oldest age from users in flutter object list...
users = [
{ id: 123, name: 'Bob', age: 25},
{ id: 345, name: 'Joe', age: 44},
...
];
First make sure your list has the correct type and format:
List<Map<String, dynamic>> users = [
{"id": 123, "name": "Bob", "age": 25},
{"id": 345, "name": "Joe", "age": 44},
{"id": 35, "name": "Joxe", "age": 40},
];
Then you can do this:
if (users != null && users.isNotEmpty) {
users.sort((a, b) => a['age'].compareTo(b['age']));
print(users.last['age']);
}
Another way would be:
if (users != null && users.isNotEmpty) {
dynamic max = users.first;
users.forEach((e) {
if (e['age'] > max['age']) max = e;
});
print(max['age']);
}
Another one:
if (users != null && users.isNotEmpty) {
print(users.fold<int>(0, (max, e) => e['age'] > max ? e['age'] : max));
}
And this one requires import 'dart:math':
if (users != null && users.isNotEmpty) {
print(users.map<int>((e) => e['age']).reduce(max));
}
I'd use the list reduce function, docs here.
var oldestUser = users.reduce((currentUser, nextUser) => currentUser['age'] > nextUser['age'] ? currentUser : nextUser)
void main() {
var users = [
{"id": 123, "name": 'Bob', "age": 25},
{"id": 345, "name": 'Joe', "age": 44},
{"id": 35, "name": 'Joxe', "age": 40},
];
users.sort(ageCompare);
print(users.first);
}
int ageCompare(u1, u2) => u2['age'] - u1['age'];
try it on https://dartpad.dartlang.org
or just one-liner
users.sort((Map u1, Map u2) => u2['age'] - u1['age']);
print(users.first);

How to rearrange map keys in dart?

I have a map like below :
{
"Future": [
{
"accountId": 57,
"firstName": "Inez",
"lastName": "Mitchell",
"middleName": "J",
}
],
"Overdue": [
{
"accountId": 5,
"firstName": "Mak",
"lastName": "Mitchell",
"middleName": "M",
}
],
"Due Today": [
{
"accountId": 59,
"firstName": "Jack",
"lastName": "Daniel",
"middleName": "P",
}
]
}
and wanted the map like in below order, Due Today first, Overdue 2nd and Future at last.
{
"Due Today": [
{
"accountId": 59,
"firstName": "Jack",
"lastName": "Daniel",
"middleName": "P",
}
],
"Overdue": [
{
"accountId": 5,
"firstName": "Mak",
"lastName": "Mitchell",
"middleName": "M",
}
],"Future": [
{
"accountId": 57,
"firstName": "Inez",
"lastName": "Mitchell",
"middleName": "J",
}
]
}
also these keys in length are 3 but sometimes we got only two of them means Due Today and Future but we have to make sure order is like 1. Due Today 2. Overdue 3. Future
There is no operation which simply rearranges the iteration order of a normal Dart map.
Dart maps usually default to using LinkedHashMap which orders its element (for example for iteration) in key insertion order.
If a key is already there, changing its value does not change the key's position in the iteration order, but any new key added will end up after all existing keys.
That provides the only avaialble way to change iteration order: Remove the key and add it again, which will put it at the end of the iteration order instead of where it previously was.
So, to reorder a map, the easiest is to create a new map:
var newMap = <String, List<Map<String, String>>>{};
for (var key in ["Due Today", "Overdue", "Future"]) {
if (map.containsKey(key)) newMap[key] = map[key];
}
Then newMap has the keys in the correct order. If you want to update your existing map to the same order, then you can do: map..clear()..addAll(newMap); afterwards.
If you want to avoid the extra map, you can delete keys and re-add them instead.
for (var key in ["Due Today", "Overdue", "Future"]) {
if (map.containsKey(key)) {
var value = map[key];
map.delete(key);
map[key] = value;
}
}
This should remove and re-add each key, if it's there at all, in the order you want them.
var keys = abc.keys.toList()..shuffle();
for(var k in keys) {
print('$k, ${abc[k]}');}
steps you need todo:
convert the map to a temp list
do your edits on the list
clear the map
copy the entries from the list back to map
**
> extension ExtensionsOnMap on Map<String, ChannelItem> {
> void replace(int index, String key, ChannelItem channelItem) {
>
> var tmpLst = this.entries.map((e) => MapEntry(e.key, e.value)).toList();
>
> tmpLst.removeAt(index);
> tmpLst.insert(index, new MapEntry(key, channelItem));
>
> this.clear();
>
> tmpLst.forEach((mapEntry) => this[mapEntry.key] = mapEntry.value);
> }
> }
**
Code:
void main(){
Map map = {
"Future": [
{
"accountId": 57,
"firstName": "Inez",
"lastName": "Mitchell",
"middleName": "J",
}
],
"Overdue": [
{
"accountId": 5,
"firstName": "Mak",
"lastName": "Mitchell",
"middleName": "M",
}
],
"Due Today": [
{
"accountId": 59,
"firstName": "Jack",
"lastName": "Daniel",
"middleName": "P",
}
]
};
for(String key in ['Due Today', 'Overdue', 'Future']){
var value = map[key];
map.remove(key);
map[key] = value;
}
print(map);
}
Output:
{
Due Today: [{
accountId: 59,
firstName: Jack,
lastName: Daniel,
middleName: P
}],
Overdue: [{
accountId: 5,
firstName: Mak,
lastName: Mitchell,
middleName: M
}],
Future: [{
accountId: 57,
firstName: Inez,
lastName: Mitchell,
middleName: J
}]
}

Rearrrange populated json result in mongoose

A simple json response for Post.find().populate("name") will return json result as follow. Note: The focus of the question is to rearrange the "name":"Alex" in json to the final structure as shown. Ignore the part that need hiding _id and __v. Thanks.
[
{
"_id": "54cd6669d3e0fb1b302e54e6",
"title": "Hello World",
"postedBy": {
"_id": "54cd6669d3e0fb1b302e54e4",
"name": "Alex",
"__v": 0
},
"__v": 0
},
...
]
How could i rearrange and display the entire json as follow?
[
{
"_id": "54cd6669d3e0fb1b302e54e6",
"title": "Hello World",
"name": "Alex"
},
...
]
You can use the lean() method to return a pure JSON object (not a mongoose document) that you can then manipulate using lodash helper methods such as map(), like in the following example:
Post.find()
.populate("name")
.lean().exec(function (err, result) {
if(result){
var posts = _.map(result, function(p) {
p.name = p.postedBy.name;
p.postedBy = undefined;
return p;
});
console.log(posts);
}
});
You can disable the "__v" attribute in your Schema definitions by setting the versionKey option to false. For example:
var postSchema = new Schema({ ... attributes ... }, { versionKey: false });
As follow-up to your question on rearranging the order of the properties in the JSON, JS does not define the order of the properties of an object. However, you
can use both the JSON.parse() and JSON.stringify() methods to change the order, for example
var json = {
"name": "Alex",
"title": "Hello World",
"_id": "54cd6669d3e0fb1b302e54e6"
};
console.log(json);
//change order to _id, title, name
var changed = JSON.parse(JSON.stringify(json, ["_id","title","name"] , 4));
console.log(k);
Check the demo below.
var json = {
"name": "Alex",
"title": "Hello World",
"_id": "54cd6669d3e0fb1b302e54e6"
};
//change order to _id, title, name
var changed = JSON.parse(JSON.stringify(json, ["_id","title","name"] , 4));
pre.innerHTML = "original: " + JSON.stringify(json, null, 4) + "</br>Ordered: " + JSON.stringify(changed, null, 4);
<pre id="pre"></pre>