How do I match a key with an object with sequelize? - mysql

Current Situation
My current Sequelize Controller looks like the below:
const getSum = async(req, res) => {
const expenses = await Expense.findAll({
attributes: [
'datepick',
'itemized_expense',
[sequelize.fn('SUM', sequelize.col('expense_amount')), 'itemized_expense_sum']],
group: ['datepick', "itemized_expense"]
})
res.status(200).json(expenses)
When I use postman, the cCurrent JSON response is below:
[
{
"datepick": "2022-10-03",
"itemized_expense": "marketing",
"itemized_expense_sum": "4000"
},
{
"datepick": "2022-10-03",
"itemized_expense": "development",
"itemized_expense_sum": "8000"
},
{
"datepick": "2022-10-03",
"itemized_expense": "welfare",
"itemized_expense_sum": "1111"
},
{
"datepick": "2022-11-14",
"itemized_expense": "wages",
"itemized_expense_sum": "6000"
},
{
"datepick": "2022-10-03",
"itemized_expense": "wages",
"itemized_expense_sum": "1111"
},
{
"datepick": "2022-11-15",
"itemized_expense": "development",
"itemized_expense_sum": "1000"
}
]
The Problem
How do I change my Sequelize Controller so that the response looks like the below?
{
key: '10/20', /*this is datepick from above*/
data: {
wages: 500000, /*this is a key-value pair of itemized_expense & itemized_expense_sum from above*/
welfare: 300000,
marketing: 500000,
development: 200000,
rental: 150000
}
},
{
key: '10/21',
data: {
wages: 300000,
welfare: 400000,
marketing: 100000,
development: 500000,
rental: 250000
}
},
I was trying to use Object.key() and map but I'm not sure if that is correct

You can use lodash package to group and rearrange items:
const items = [
{
"datepick": "2022-10-03",
"itemized_expense": "marketing",
"itemized_expense_sum": "4000"
},
{
"datepick": "2022-10-03",
"itemized_expense": "development",
"itemized_expense_sum": "8000"
},
{
"datepick": "2022-10-03",
"itemized_expense": "welfare",
"itemized_expense_sum": "1111"
},
{
"datepick": "2022-11-14",
"itemized_expense": "wages",
"itemized_expense_sum": "6000"
},
{
"datepick": "2022-10-03",
"itemized_expense": "wages",
"itemized_expense_sum": "1111"
},
{
"datepick": "2022-11-15",
"itemized_expense": "development",
"itemized_expense_sum": "1000"
}
]
const groupedItems = _.groupBy(items, x => x.datepick)
const keys = Object.keys(groupedItems)
const mappedItems = keys.map(x => ({
key: x,
data: _.fromPairs(groupedItems[x].map(item => [item.itemized_expense, item.itemized_expense_sum])
)
}))
result = mappedItems
result:
[
{
"key": "2022-10-03",
"data": {
"marketing": "4000",
"development": "8000",
"welfare": "1111",
"wages": "1111"
}
},
{
"key": "2022-11-14",
"data": {
"wages": "6000"
}
},
{
"key": "2022-11-15",
"data": {
"development": "1000"
}
}
]
You can try this code in this lodash sandbox

Related

type '(dynamic) => SBranch' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform

I have tried several ways to access the data but the result is still the same where the type is a map and I can't convert it to a list of my model so I hope to get some help and I am thankful to you
my Repo
Future getdata(apiUrl) async {
http.Response response = await http.get(Uri.parse(_url + apiUrl));
try {
if (response.statusCode == 200) {
print('dtaa serve done 200');
var body= jsonDecode(response.body);
print(body.runtimeType);
print(body.runtimeType);
return body;
} else {
print("its empty first");
return {};
}
} catch (e) {
print(e.toString() + "first");
return {};
}
my Cubit
void getSBranchData(Service service) async {
try { print("loding SBranchData");
sBranches = await repo.getSBranches(service.id);
print(sBranches.toString()+" Cubit");
emit(SBranchDataState(sBranches,service));
print("loded SBranchData");
} catch (e) {
print(e.toString() + "sec");
}
is this Right
my model
SBranch(
{this.id,
this.sbranchName,
this.sbranchDisc,
this.sbranchImg,
this.parentSbranch,
this.serviceId,
this.childSbranch});
SBranch.fromJson(Map<String, dynamic> json) {
id = json['id'];
sbranchName = json['sbranch_name'];
sbranchDisc = json['sbranch_disc'];
sbranchImg = json['sbranch_img'];
parentSbranch = json['parent_sbranch'];
serviceId = json['service_id'];
if (json['child_sbranch'] != null) {
childSbranch = <ChildSbranch>[];
json['child_sbranch'].forEach((v) {
childSbranch!.add(new ChildSbranch.fromJson(v));
});
json
[
{
"id": 1,
"sbranch_name": "mn,.m.",
"sbranch_disc": "lmlmlm.",
"sbranch_img": "",
"parent_sbranch": 0,
"service_id": "1",
"child_sbranch": [
{
"id": 3,
"sbranch_name": "mn,.m.",
"sbranch_disc": "lmlmlm.",
"sbranch_img": "",
"parent_sbranch": 1,
"service_id": "",
"child_sbranch": []
}
]
},
{
"id": 2,
"sbranch_name": "mn,.m.",
"sbranch_disc": "lmlmlm.",
"sbranch_img": "",
"parent_sbranch": 0,
"service_id": "2",
"child_sbranch": [
{
"id": 4,
"sbranch_name": "mn,.m.",
"sbranch_disc": "lmlmlm.",
"sbranch_img": "",
"parent_sbranch": 2,
"service_id": "",
"child_sbranch": []
}
]
},
{
"id": 3,
"sbranch_name": "mn,.m.",
"sbranch_disc": "lmlmlm.",
"sbranch_img": "",
"parent_sbranch": 1,
"service_id": "",
"child_sbranch": []
},
{
"id": 4,
"sbranch_name": "mn,.m.",
"sbranch_disc": "lmlmlm.",
"sbranch_img": "",
"parent_sbranch": 2,
"service_id": "",
"child_sbranch": []
}
]
thanks for your Time
vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv** *
v*

JSON only reading first element of array

I am working on a discord bot using Typescript, and I am having a problem reading from the config.JSON file.
This is the read vars function:
fs.readFile('config.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
config = JSON.parse(data);
console.log(config);
const store = config.configstore[0];
roster = config.roster[0];
}});
and this is the config.json file:
{
"configstore": [
{"prefix": "!!"},
{"wallTime": 5},
{"bufferTime": 15},
{"wall": "false"},
{"buffer": "false"},
{"lastWallTime": "-1"},
{"lastBufferTime": "-1"},
{"wallCheckRole": "Role"},
{"bubfferCheckRole": "Role"}
],
"roster": [
{"discID":"discordID","ign":"IGN"}
]
}
When I print out the raw 'config' variable it prints this:
{
configstore: [
{ prefix: '!!' },
{ wallTime: 5 },
{ bufferTime: 15 },
{ wall: 'false' },
{ buffer: 'false' },
{ lastWallTime: '-1' },
{ lastBufferTime: '-1' },
{ wallCheckRole: 'Role' },
{ bubfferCheckRole: 'Role' }
],
roster: [ { discID: 'DiscordID', ign: 'IGN' } ]
}
But when I print the store variable it prints this:
{ prefix: '!!' }
The roster is normal as well.
The roles and ids are strings, but I changed it since I don't want them leaked.
These are some examples of what you are probably trying to achieve:
let config1 = {
"configstore": [
{"prefix": "!!"},
{"wallTime": 5},
{"bufferTime": 15},
{"wall": "false"},
{"buffer": "false"},
{"lastWallTime": "-1"},
{"lastBufferTime": "-1"},
{"wallCheckRole": "Role"},
{"bubfferCheckRole": "Role"}
],
"roster": [
{"discID":"discordID","ign":"IGN"}
]
}
let config2 = {
"configstore": [
{
"prefix": "!!",
"wallTime": 5,
"bufferTime": 15,
"wall": "false",
"buffer": "false",
"lastWallTime": "-1",
"lastBufferTime": "-1",
"wallCheckRole": "Role",
"bubfferCheckRole": "Role"
}
],
"roster": [
{"discID":"discordID","ign":"IGN"}
]
}
//prints {"prefix":"!!"}
console.log("configstore1:", JSON.stringify(config1.configstore[0]));
//prints {"discID":"discordID","ign":"IGN"}
console.log("roster1:", JSON.stringify(config1.roster[0]));
//prints {"prefix":"!!","wallTime":5,"bufferTime":15,"wall":"false","buffer":"false","lastWallTime":"-1","lastBufferTime":"-1","wallCheckRole":"Role","bubfferCheckRole":"Role"}
console.log("configstore2:", JSON.stringify(config2.configstore[0]));
//prints {"discID":"discordID","ign":"IGN"}
console.log("roster2:", JSON.stringify(config2.roster[0]));

{this.state.object} Objects are not valid as a React child

I have a response json like this:
{
"variables": {
"lock": 0,
"pos": 55,
"pos_on": 55,
"pos_off": 150
},
"id": "11",
"name": "Lock_table_2",
"hardware": "esp8266",
"connected": true
}
and I try to show the lock value in 'variables' object
so I write
constructor(props) {
super(props)
this.state = {
dock_1: {}, // define a empty json
dock_2: {},
dock_3: {},
}
}
pingIP() {
axios
.get('http://192.168.50.225:8888/test_check')
.then(response => {
let data = response.data.list; // return value is a list
this.setState({ // every 2 sec setState
dock_1: data[0], // data[0] -> 192.168.50.40's json
dock_2: data[1],
dock_3: data[2],
})
})
}
render(){
return (
<p>{this.state.dock_1.variables.lock}</p>
);
}
but I got this error
in here
So I tried this
render(){
return (
<p>{this.state.dock_1.variables}</p>
);
}
then here comes the another error message
in here
here is the get request return value
{
"list": [
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_1",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
},
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_2",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
},
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_3",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
}
]
}
the return value is a list
in order to get first value so I wrote data[0], data1 ...
what's happening in here?
I think your response is an array of 3 items like this:
[
{
variables: {
lock: 0,
pos: 55,
pos_on: 55,
pos_off: 150
},
id: "11",
name: "Lock_table_2",
hardware: "esp8266",
connected: true
},
{
variables: {
lock: 1,
pos: 44,
pos_on: 56,
pos_off: 151
},
id: "11",
name: "Lock_table_3",
hardware: "esp8267",
connected: false
},
{
variables: {
lock: 2,
pos: 45,
pos_on: 57,
pos_off: 152
},
id: "11",
name: "Lock_table_4",
hardware: "esp8268",
connected: true
}
]
So you can access the dock 1 variable lock using Inline If with Logical && Operator to prevent null exception.
<p>{this.state.dock_1.variables && this.state.dock_1.variables.lock}</p>
A sample working codesandbox with a fake api:
https://codesandbox.io/s/stoic-chaplygin-r1yxd

Angular/Ionic - How to group data from two JSON source?

I want to group data JSON into accordion list in Ionic. How can I do that with two JSON source?
Previously I did successfully with only one JSON.
I have two JSON that look like this.
The one :
{
{
"ObjectId": '001',
"ObjectName": 'Fruits'
},
{
"ObjectId": '002',
"ObjectName": 'Vegetables'
}
}
The other one :
{
{
"Name": 'Apple',
"Color": 'Red',
"ObjectId": '001'
},
{
"Name": 'Eggplant',
"Color": 'Purple',
"ObjectId": '002'
},
{
"Name": 'Banana',
"Color": 'Yellow',
"ObjectId": '001'
},
{
"Name": 'Spinach',
"Color": 'Green',
"ObjectId": '002'
},
{
"Name": 'Garlic',
"Color": 'White',
"ObjectId": '002'
},
}
Here my expected result image :
Accordion-List
I've found the solution, but i'm not sure my method is the best way.
Here is my method :
// GET DATA API
let getObjectApi = this.dataProvider.getObjectUrl();
new Promise(resolve => {
getObjectApi.subscribe(data => {
resolve(data);
this.apiObjectData = data;
// LOOPING OBJECT DATA
for (let i = 0; i < this.apiObjectData.length; i++) {
const objItem = data[i];
// GET OBJECT ITEM BY ObjectId
let getObjectItem = this.getObjectItemByObjectId('ObjectId', objItem['ObjectId']);
// PUSH THE DATA
this.apiDataResult.push({
'dataObject': objItem,
'dataObjectItem' : getObjectItem
});
}
}, err => {
console.log(err);
});
});
And here this.getObjectItemByObjectId() method :
getObjectItemByObjectId(column, value) {
let result:any = [];
let dataApi: any = [];
let getObjectItemApi = this.dataProvider.getObjectItemUrl();
new Promise(resolve => {
getObjectItemApi.subscribe(data => {
resolve(data);
dataApi = data;
for (let i = 0; i < dataApi.length; i++) {
const element = dataApi[i];
if (element[column] == value) {
result.push(element);
}
}
}, err => {
console.log(err);
});
});
return result;
}
And the result is something like this :
{
{
"dataObject": {
"ObjectId": '001',
"ObjectName": 'Fruits'
},
"dataObjectItem": {
{
"Name": 'Apple',
"Color": 'Red',
"ObjectId": '001'
},
{
"Name": 'Banana',
"Color": 'Yellow',
"ObjectId": '001'
}
}
},
{
"dataObject": {
"ObjectId": '002',
"ObjectName": 'Vegetables'
},
"dataObjectItem": {
{
"Name": 'Eggplant',
"Color": 'Purple',
"ObjectId": '002'
},
{
"Name": 'Spinach',
"Color": 'Green',
"ObjectId": '002'
},
{
"Name": 'Garlic',
"Color": 'White',
"ObjectId": '002'
}
}
}
}
That's all!
If there is a better way than my method, please let me know! And sorry if something is goes wrong. Thank you in advance !!

jQuery.Deferred exception: Cannot read property 'models' of undefined

I'm not sure how to debug this error.
I have a kendo grid that allows users to drag and drop to sort rows and also allows users to update a cell in those rows. However after adding the sort functionality I get this error when trying to update a row:
jQuery.Deferred exception: Cannot read property 'models' of undefined TypeError: Cannot read property 'models' of undefined
I have this code:
#(Html.Kendo().Grid<DocumentProperties>(Model.CurrentList)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.ID).Visible(false);
columns.Bound(p => p.SortOrder).Visible(false);
columns.Bound(p => p.DisplayText).Title("Title");
columns.Bound(p => p.FileName).Title("File Name");
columns.Bound(p => p.ID).ClientTemplate(#Html.ActionLink("View", "ViewDocument", new { id = "did" }, new { target = "_blank" }).ToHtmlString().Replace("did", "#: ID #")).Title("").Width(80); //creates link to view the uploaded document
columns.Bound(p => p.ID).ClientTemplate(#Html.ActionLink("Remove", "DeleteDocument", new { id = "did" }, new { onclick = "return confirm('Are you sure you want to delete this document?');", style = "color:Red;" }).ToHtmlString().Replace("did", "#: ID #")).Title("").Width(80);
columns.Command(commands =>
{
commands.Edit(); // The "edit" command will edit and update data items.
}).Title("").Width(80);
})
.DataSource(dataSource => dataSource
.Ajax()
.Update(update => update.Action("DocAttributeUpdate", "Blurb")) // Action invoked when the user saves an updated data item.
.Events(events => events.Error("error_handler"))
.PageSize(20)
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.ID); // Specify the property which is the unique identifier of the model.
model.Field(p => p.ID).Editable(false); // Make the ID property not editable.
model.Field(p => p.SortOrder).Editable(false); // Make the SortOrder property not editable.
model.Field(p => p.FileName).Editable(false); // Make the FileName property not editable.
model.Field(p => p.DisplayText).Editable(true); // Make the DisplayText property editable.
})
)
.Sortable(sortable => sortable
.Enabled(true)
)
.Pageable(pageable => pageable
//.Refresh(true) Need to figure this out. Doesn't refresh properly.
.PageSizes(true)
.ButtonCount(5))
.Resizable(r => r.Columns(true))
.Selectable(selectable => selectable.Mode(GridSelectionMode.Single).Type(GridSelectionType.Row)) //make each row selectable
)
#(Html.Kendo().Sortable() //this adds the cool drag and drop sorting
.For("#Grid")
.Filter("table > tbody > tr")
.Cursor("move")
.HintHandler("noHint")
.PlaceholderHandler("placeholder")
.ContainerSelector("#Grid tbody")
.Events(events => events.Change("onChange"))
)
<script type="text/javascript">
var noHint = $.noop;
function placeholder(element) {
return element.clone().addClass("k-state-hover").css("opacity", 0.65);
}
function onChange(e) {
var grid = $("#Grid").data("kendoGrid"),
skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip,
dataItems = grid.dataSource.data(),
dataItem = grid.dataSource.getByUid(e.item.data("uid")); //grab your item and give it a new index. Then remove the item from the list and place in the new index.
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
var dataList = [];
for (var i = 0; i < dataItems.length; i++) {
dataList[i] = {
ID: dataItems[i].ID,
ClientId: dataItems[i].ClientId,
SortOrder: i,
DisplayText: dataItems[i].DisplayText,
Type: dataItems[i].Type,
MimeType: dataItems[i].MimeType,
FileName: dataItems[i].FileName
};
}
$.ajax({
url: "/Blurb/SaveSortOrder",
type: "POST",
data: {
data: JSON.stringify(dataList) //send our json string back to the server for sorting
}
})
};
When I remove the code for:
#(Html.Kendo().Sortable()
The update button works again, but I don't have my drag and drop sorting anymore.
jQuery Script:
<script>
jQuery(function() {
jQuery("#Grid").kendoGrid({
"columns": [{
"title": "Title",
"headerAttributes": {
"data-field": "DisplayText",
"data-title": "Title"
},
"field": "DisplayText",
"encoded": true,
"editor": "\u003cinput class=\"text-box single-line\" id=\"DisplayText\" name=\"DisplayText\" type=\"text\" value=\"\" /\u003e\u003cspan class=\"field-validation-valid\" data-valmsg-for=\"DisplayText\" data-valmsg-replace=\"true\"\u003e\u003c/span\u003e"
}, {
"title": "File Name",
"headerAttributes": {
"data-field": "FileName",
"data-title": "File Name"
},
"field": "FileName",
"encoded": true
}, {
"headerAttributes": {
"data-field": "ID",
"data-title": ""
},
"width": "80px",
"template": "\u003ca href=\"/Blurb/ViewDocument/#: ID #\" target=\"_blank\"\u003eView\u003c/a\u003e",
"field": "ID",
"encoded": true
}, {
"headerAttributes": {
"data-field": "ID",
"data-title": ""
},
"width": "80px",
"template": "\u003ca href=\"/Blurb/DeleteDocument/#: ID #\" onclick=\"return confirm(\u0027Are you sure you want to delete this document?\u0027);\" style=\"color:Red;\"\u003eRemove\u003c/a\u003e",
"field": "ID",
"encoded": true
}, {
"width": "80px",
"command": [{
"name": "edit",
"buttonType": "ImageAndText",
"text": "Edit"
}]
}],
"pageable": {
"pageSizes": [5, 10, 20],
"buttonCount": 5
},
"sortable": true,
"selectable": "Single, Cell",
"resizable": true,
"scrollable": false,
"editable": {
"confirmation": "Are you sure you want to delete this record?",
"confirmDelete": "Delete",
"cancelDelete": "Cancel",
"mode": "inline",
"create": true,
"update": true,
"destroy": true
},
"messages": {
"noRecords": "No records available."
},
"dataSource": {
"type": (function() {
if (kendo.data.transports['aspnetmvc-ajax']) {
return 'aspnetmvc-ajax';
} else {
throw new Error('The kendo.aspnetmvc.min.js script is not included.');
}
})(),
"transport": {
"read": {
"url": ""
},
"prefix": "",
"update": {
"url": "/Blurb/DocAttributeUpdate"
}
},
"pageSize": 20,
"page": 1,
"total": 3,
"error": error_handler,
"schema": {
"data": "Data",
"total": "Total",
"errors": "Errors",
"model": {
"id": "ID",
"fields": {
"ID": {
"editable": false,
"type": "number"
},
"ClientId": {
"type": "number"
},
"SortOrder": {
"editable": false,
"type": "number",
"defaultValue": null
},
"DisplayText": {
"type": "string"
},
"Type": {
"type": "string"
},
"MimeType": {
"type": "string"
},
"FileName": {
"editable": false,
"type": "string"
},
"Document": {
"type": "object"
}
}
}
},
"data": {
"Data": [{
"ID": 440,
"ClientId": 16,
"DisplayText": "Test Document",
"FileName": "3182AscensionRecipientsDashboard (5).pdf",
"Type": "Document",
"MimeType": "application/pdf",
"Document": {
"ID": 0,
"DocumentAttributeId": 0,
"FileContent": null ,
"Content": null
},
"SortOrder": 0
}, {
"ID": 5,
"ClientId": 16,
"DisplayText": "Summary Plan Description",
"FileName": "Summary Plan Description.pdf",
"Type": "Document",
"MimeType": "application/pdf",
"Document": {
"ID": 0,
"DocumentAttributeId": 0,
"FileContent": null ,
"Content": null
},
"SortOrder": 1
}, {
"ID": 6,
"ClientId": 16,
"DisplayText": "Summary Annual Report",
"FileName": "SUMMARY ANNUAL REPORT.pdf",
"Type": "Document",
"MimeType": "application/pdf",
"Document": {
"ID": 0,
"DocumentAttributeId": 0,
"FileContent": null ,
"Content": null
},
"SortOrder": 2
}],
"Total": 3,
"AggregateResults": null
}
}
});
});
</script>
I had to approach edit a bit differently to get this work, although I might still try to figure out why my original way wasn't working.
I had to add the toolbar feature of kendo and make the cell editable:
.ToolBar(toolBar =>
{
toolBar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))