search for an item into list<map> - flutter

Good Morning everyone, I want ask a question if I have a list of map like this
[{
id: 1,
title: Medicine 500,
price: 100,
image: http://secret-taiga-11502.herokuapp.com/images/medicines,
quantity: 1,
pharmacyid: 15,
medicineID: 500
}]
and I want to search for an item medicineID to make a compression
how can I do this
this my code
var extractMap = cubit.myItems.map(
(element) => Map.fromEntries(
[MapEntry('medicine_id', element['medicineID']),])).toList();
if(
extractMap.contains(
cubit.onePharmacyModel!.data!.activeMedicines![index].id!.toInt())
){
cubit.updateQuery(
++cubit.myItems[index]["quantity"],
cubit.myItems[index]['id'],
cubit.onePharmacyModel!.data!.id!.toInt()
);
Fluttertoast.showToast(msg: "cart updated");
}else{
cubit.insertToDatabase(
title: cubit.onePharmacyModel!.data!.activeMedicines[index].name.toString(),
price: cubit.onePharmacyModel!.data!.activeMedicines[index].pivot!.price!.toString(),
image: cubit.onePharmacyModel!.data!.activeMedicines[index].photo.toString(),
quantity: 1,
pharmacyID: cubit.onePharmacyModel!.data!.id!.toInt(),
medicineID: cubit.onePharmacyModel!.data!.activeMedicines[index].id!.toInt());
Fluttertoast.showToast(msg: "product added to cart");
}
the general idea of code that the user when add a product to the cart I'm checking if it's already exist or not if yes => I'll update the amount of this product, if no => T'll insert it into my Database

Try something like:
if (myItems.any((e) => e['medicineID'] == 58)) {
// ...
}

Related

How to cancel all chnages in row

I have a ag grid table with edit enabled on each cell. I want to reset all changes the user has made on specfic button on click.
To achieve this we need to keep our original data separate from what the user will edit - this is done by making a deep copy:
const originalData = [{ make: 'Toyota', model: 'Celica', price: 35000},
{ make: 'Ford', model: 'Mondeo', price: 32000 },
{ make: 'Porsche', model: 'Boxster', price: 72000 },
];
let copyData = originalData.map((d) => ({ ...d }));
After the cells have been edited - in our function we remake our deep copy then call SetRowData on the deep copy:
const resetChanges = () => {
copyData = originalData.map((d) => ({ ...d }));
gridDataRef.current.gridApi.setRowData(copyData);
};
Heres a live example: https://plnkr.co/edit/1GpqhekV2A5XePSn?open=index.jsx

applyTransaction remove not working with id

I'm using ag-grid in Angular9 project. I'm using Transactions to do CRUD operations in grid when my backend request resolve. I need to provide RowNodeId myself, i dont want to use object-references as i have large data set.
Thing is, i've provided the ID and i can add/update item in the grid but i'm unable to delete the item. In Doc it mentions, you only need to provide id to remove the item but i'm getting the following error.
Here's the code.
class HostAppListPage
{
#ViewChild('agGrid', {static: true}) grid:AgGridAngular;
constructor()
{
}
ngOnInit()
{
this.grid.getRowNodeId = (data) => {
return data.entityId;
};
this.columns = [
{headerName: 'App Name', field: 'name', rowDrag: true, headerCheckboxSelection: true, checkboxSelection: true},
{headerName: 'App Id', field: 'id'},
{headerName: 'Compatibility', field: COMPATIBILITY'},
{headerName: 'Creation', field: 'createdAtToString'},
{headerName: 'Last Update', field: 'updatedAtToString'}
];
}
deleteRow()
{
let ids = this.gridApi.getSelectedNodes()
// .map((row) => {
// return {id: row.entityId}
// return row.entityId;
// });
console.log(ids);
this.grid.api.applyTransaction({remove: ids});
}
I tried both with and without map statement, nothing worked
but my Add and Update works fine.
Replace map with following code.
.map((row) => {
return {entityId: row.data.entityId};
});
it should be the the same field (entityId) which i set in getRowNodeId function.
In a typical situation, where one does not define a getRowNodeId, one should be able to do:
const removeData: any[] = [{id: rowNode0.id}, {id: rowNode1.id}, ...];
applyTransaction({remove: removeData});
where rowNode0, rowNode1, etc. are the nodes you want to remove.
However when you provide your own getRowNodeId callback, ag-grid will fetch the id's by applying your callback on the data you provided. Therefore, the name(s) in the data must match those used in your callback. That's why return {id: row.entityId} doesn't work, but return {entityId: row.entityId} does.
In other words, if one defines:
this.grid.getRowNodeId = (data) => {
return data.column1 + data.column5 + data.column2;
};
Then one would need to provide
const removeData: any[] = [
{column1: 'a1', column2: 'b1', column5: 'c1'},
{column1: 'a2', column2: 'b2', column5: 'c2'},
{column1: 'a3', column2: 'b3', column5: 'c3'},
];
so that ag-grid would have all the names it needs to find the id's via the given getRowNodeId.

Building a List in actions-on-google Nodejs v2

I may be missing something really obvious, but I haven't figured out how I can build a List programatically in v2 of tne actions-on-google Nodejs client library.
In other words, I want to do something like the conv.ask code below, but don't know the items beforehand, so need to create a list, add the items to the list, and then ask the list in dynamic way. I could do this in v1 with:
var rList = app.buildList("Please select one option:");
for (var r =0; r < resp_text.length; r++) {
rList.addItems(app.buildOptionItem(resp_value[r], resp_matches[r]).setTitle(resp_text[r]));
}
app.askWithList(question_str, rList);
... so am basically looking for the v2 equivalent of the above.
Any help appreciated, thanks!
conv.ask(new List({
title: 'Things to learn about',
items: {
// Add the first item to the list
'MATH_AND_PRIME': {
synonyms: [
'math',
'math and prime',
'prime numbers',
'prime',
],
title: 'Title of the First List Item',
description: '42 is an abundant number',
image: new Image({
url: 'https://example.com/math_and_prime.jpg',
alt: 'Math & prime numbers',
}),
},
// Add the second item to the list
'EGYPT': {
synonyms: [
'religion',
'egypt',
'ancient egyptian',
],
title: 'Ancient Egyptian religion',
description: '42 gods ruled on the fate of the dead in the afterworld',
image: new Image({
url: 'http://example.com/egypt',
alt: 'Egypt',
}),
},
// Add the last item to the list
'RECIPES': {
synonyms: [
'recipes',
'recipe',
'42 recipes',
],
title: '42 recipes in 42 ingredients',
description: 'A beautifully simple recipe',
image: new Image({
url: 'http://example.com/recipe',
alt: 'Recipe',
}),
},
},
}));
Ok, answering my own question just in case it will help someone else...
The way (or at least one way) to do this is to dynamicaly create an item array and using that in the list constructor:
var ritems = {}
for (var r=0; r < resp_text.length; r++) {
ritems[resp_value[r]] = {
synonyms: [resp_matches[r]],
title: resp_text[r]
}
}
conv.ask(question_str);
conv.ask(new List({
title: "Please select one option:",
items: ritems
}))

Sencha touch 2 filterby() not updating records

I have a nested list on one of the pages of a Tabbed Panel app that is pulling data from "offices.json"
I should like to be able to filter this list when a user clicks on a toolbar button. However my filterBy() function doesn't update the store and the list of offices I can see, even though I can see in the console it is iterating the records and finding a match. What am I doing wrong?
(And yes I have tried doing s.load() both before and after the filterBy to no avail!)
toolbar:{
items:[{
text: 'Near you',
id: 'btnNearYou',
xtype: 'button',
handler: function() {
s = Ext.StoreMgr.get('offices');
s._proxy._url = 'officesFLAT.json';
console.log("trying to filter");
s.filterBy(function(record) {
var search = new RegExp("Altrincham", 'i');
if(record.get('text').match(search)){
console.log("did Match");
return true;
}else {
console.log("didnt Match");
return false;
}
});
s.load();
}
}]
For the record I'm defining my store like so:
store: {
type: 'tree',
model: 'ListItem',
id: 'offices',
defaultRootProperty: 'items',
proxy: {
type: 'ajax',
root: {},
url: 'offices.json',
reader: {
type: 'json',
rootProperty: 'items'
}
}
}
No need to recreate the regex each time, cache it outside.
You can simplify the code a lot (see below).
Why are you calling load directly after? That's going to send it to the server and it will just retrieve the same dataset.
toolbar: {
items: [{
text: 'Near you',
id: 'btnNearYou',
xtype: 'button',
handler: function() {
s = Ext.StoreMgr.get('offices');
s._proxy._url = 'officesFLAT.json';
var search = /Altrincham/i;
s.filterBy(function(record) {
return !!record.get('text').match(search);
});
}
}]
}

Map Reduce Mongodb Node JS native driver

I'm working with the Mongodb native driver using a Map reduce function. Basically I have a mediaId as a key and want to count how many medias loaded and started per mediaId.
So what I've done was:
var map = function(){
emit(this.media.id, {
count: 1,
played: 0,
ph: this.project.id,
title: this.media.title,
media: this.media.id,
origin: this.origin,
thumbnail: this.media.thumbnail,
mediaDuration: this.media.mediaDuration,
state: this.state
});
};
var reduce = function(k, vals) {
result = {
count: 0,
played: 0,
ph: '',
title: '',
media: '',
origin: '',
thumbnail: '',
mediaDuration: 0,
state: ''
};
vals.forEach(function(doc){
result.count += doc.count;
result.ph = doc.ph;
result.title = doc.title;
result.media = doc.media;
result.thumbnail = doc.thumbnail;
result.mediaDuration = doc.mediaDuration;
result.state = doc.state;
result.origin = doc.origin;
if(doc.state === "started") {
result.played += 1;
}
});
return result;
};
In my test collection I have 2 different mediaIds. One with 553 objects and another one with just 1 object. I've putted all in the "started" state to test this so basically the number of count should be equal to the number of played.
When I run the Map/Reduce function it returns to me ( I used the "toArray" function of the mongodb native driver):
[ { _id: '12398asdsa9802193810asd120',
value:
{ count: 1,
played: 0,
ph: '123213ased12231',
title: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
media: '1xxxxxxxxxxxxxxxxxxxxxxxxxxx1',
origin: 'http://www.google.com',
thumbnail: 'http://cache.ohinternet.com/images/0/0e/Forever_Alone.png',
mediaDuration: 12321321,
state: 'started' } },
{ _id: '2c9f94b42f5b5114012f5b92ea430066',
value:
{ count: 553,
played: 155,
ph: '316',
title: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
media: '2xxxxxxxxxxxxxxxxxxxxxxxxxxx2',
origin: 'http://localhost:9000/views/index.html',
thumbnail: null,
mediaDuration: null,
state: 'started' } } ]
It seems that one I have just one object the reduce function isn't called ( I did some tests with another collection with more than 100 mediaIds and the behavior was identical. Does anyone have an idea of what is wrong with that?
Thanks A LOT for your time,
Cheers.
I sort of solved the "issue".
I did the filter on the Map Function and not on the Reduce function. Something like this:
var map = function(){
if(this.media.state==="started") {
var played = 1;
}else{var played = 0;}
emit(this.media.id, {
count: 1,
played: played,
ph: this.project.id,
title: this.media.title,
media: this.media.id,
origin: this.origin,
thumbnail: this.media.thumbnail,
mediaDuration: this.media.mediaDuration,
state: this.state
});
};
Hope it helps anyone that is having the same "problem"