[
{
"id": 200,
"date_created": "2021-01-14T17:15:55",
"sale": "2500.00",
},
{
"id": 201,
"date_created": "2021-01-15T15:10:30",
"sale": "2000.00",
},
{
"id": 202,
"date_created": "2021-02-4T11:14:10",
"sale": "4000.00",
}
]
I am unable to sum it by the monthly basis in react js or next js.
Can someone guide me on how can I do it in React?
I want the output as:
monthly basis.
For Jan total sum = 4500
For Feb total sum = 4000
etc...
You have to browse your array and to add each sale.
Example :
const a = [
{
"id": 200,
"date_created": "2021-01-14T17:15:55",
"sale": "2500.00",
},
{
"id": 201,
"date_created": "2021-01-15T15:10:30",
"sale": "2000.00",
},
{
"id": 202,
"date_created": "2021-02-4T11:14:10",
"sale": "4000.00",
}
]
const sum = a.reduce((previous, current) => previous + new Number(current.sale), 0)
console.log(sum)
Related
I have an array with objects having "category" & "price" properties among others, in the Angular application I need to display only unique values of "category" property (Example: Economy, Premium & Deluxe) along with the lowest price in that category. I tried filtering it but was unable to achieve it. So can you please help how this can be achieved in Angular? Thank you.
In this example, I need to show:
Economy - Starts from 250USD
Premium - Starts from 400USD
Deluxe - Starts from 600USD
"hotelRooms": [
{
"price": {
"total": 250,
"currency": "USD"
},
"category": "Economy",
"subcategory": "single",
},
{
"price": {
"total": 350,
"currency": "USD"
},
"category": "Economy",
"subcategory": "double",
},
{
"price": {
"total": 450,
"currency": "USD"
},
"category": "Economy",
"subcategory": "family",
},
{
"price": {
"total": 400,
"currency": "USD"
},
"category": "Premium",
"subcategory": "single",
},
{
"price": {
"total": 500,
"currency": "USD"
},
"category": "Premium",
"subcategory": "double",
},
{
"price": {
"total": 600,
"currency": "USD"
},
"category": "Deluxe",
"subcategory": "single",
},
{
"price": {
"total": 700,
"currency": "USD"
},
"category": "Deluxe",
"subcategory": "double",
}
]
And in Angular:
<div *ngFor="let room of hotelRooms">
<span class="bold">{{ room.category }}</span> - Starts from {{ room.price.total}}{{ room.price.currency}}
</div>
From what I understand on this question, you need to group by category and next get the lowest price.amount for each category.
Concept (TL;DR)
Group By Category
1.1 Create an array for each category if the category array does not exist. Else reuse the created category array.
1.2 From each category array, find the lowest record based on price.amount.
1.3 If the result (from 1.2) return no value (undefined), first reset category array to empty array and add the current record to the category array. This ensures that each category will only have 1 record with the lowest price. Else just ignore it.
Data Transformation
2.1 Get the item from each category via iterate with key. It will return arrays.
2.2 Concat multiple arrays (from 2.1) into one array.
let groupByCategories = [];
groupByCategories = this.hotelRooms.reduce(function (previous, current) {
previous[current.category] = previous[current.category] || [];
let lowest = previous[current.category].find(
(x) =>
x.price.total < current.price.total
);
if (!lowest) {
previous[current.category] = [];
previous[current.category].push(current);
}
return previous;
}, Object.create(null));
this.hotelRooms = [].concat(
...Object.keys(groupByCategories).map((key) => {
return groupByCategories[key];
})
);
Sample Demo on StackBlitz
How can I update a value in a document based on applying functions to another field (which is in a different embedded document)?
With the sample data below, I want to
get the col field for the farm having id 12
multiply that by 0.025
add the current value of the statistic.crypt field
ensure the value is a double by converting it with $toDouble
store the result back into statistic.crypt
data:
{
"_id": {
"$oid": "6128c238c144326c57444227"
},
"statistic": {
"balance": 112570,
"diamond": 14,
"exp": 862.5,
"lvl": 76,
"mn_exp": 2.5,
"lvl_mn_exp": 15,
"coll_ms": 8047,
"all_exp": 67057.8,
"rating": 0,
"crypt": 0
},
"inventory": {
"farm": [{
"id": 12,
"col": 100,
"currency": "diamond",
"cost": 2,
"date": "2021-09-02 18:58:39"
}, {
"id": 14,
"col": 1,
"currency": "diamond",
"cost": 2,
"date": "2021-09-02 16:57:08"
}],
"items": []
},
...
}
My initial attempt is:
self.collection
.update_many({"inventory.farm.id": 12}, [{
"$set": {
"test": {
'$toDouble': {
"$sum": [
{'$multiply':["$inventory.farm.$[].col", 0.025]},
'$test'
]
}
} }
},])
This does not work as it applies to test rather than statistic.crypt, and I cannot figure out how to modify it to apply to statistic.crypt.
A field can be updated based on another in the following stages:
add a field containing the farm
set statistic.crypt to the result of the mathematical expression (applied to the newly embedded farm)
remove extra fields
In code:
self.collection.update_many({"inventory.farm.id": 12 }, [
{
$addFields: {
hh: {
$filter: {
input: "$inventory.farm",
as: "z",
cond: { $eq: ["$$z.id", 12] },
},
},
},
},
{
$set: {
"statistic.crypt": {
$toDouble: {
$sum: [
{
$multiply: [{ $first: "$hh.col" }, 0.025],
},
"statistic.crypt",
],
},
},
},
},
{
$project: {
id_pr: 1,
id_server: 1,
role: 1,
warns: 1,
id_clan: 1,
statistic: 1,
design: 1,
date: 1,
inventory: 1,
voice: 1,
},
},)
So I have successfully managed to parse the JSON data shown below:
[
{
"IsRecentlyVerified": false,
"ID": 136888,
"UUID": "254B0B07-E7FC-4B4B-A37C-899BCB9D7261",
"DataProviderID": 18,
"DataProvidersReference": "0a9fdbb17feb6ccb7ec405cfb85222c4",
"OperatorID": 3,
"UsageTypeID": 1,
"AddressInfo": {
"ID": 137234,
"Title": "Ballee Road Park & Share",
"AddressLine1": "Ballee Road",
"Town": "Ballymena",
"Postcode": "BT42 2HD",
"CountryID": 1,
"Latitude": 54.844648,
"Longitude": -6.273606,
"AccessComments": "Ballee Road Park and Share, Ballymena",
"RelatedURL": "http://pod-point.com",
"Distance": 3.812940207797744,
"DistanceUnit": 2
},
"Connections": [
{
"ID": 191571,
"ConnectionTypeID": 25,
"Reference": "1",
"StatusTypeID": 50,
"LevelID": 2,
"Amps": 32,
"Voltage": 400,
"PowerKW": 22,
"CurrentTypeID": 20
},
{
"ID": 191572,
"ConnectionTypeID": 25,
"Reference": "2",
"StatusTypeID": 50,
"LevelID": 2,
"Amps": 32,
"Voltage": 400,
"PowerKW": 22,
"CurrentTypeID": 20
}
],
"StatusTypeID": 0,
"DateLastStatusUpdate": "2020-02-21T15:15:00Z",
"MetadataValues": [
{
"ID": 6740,
"MetadataFieldID": 4,
"ItemValue": "Contains public sector information licensed under the Open Government Licence v2.0. http://www.nationalarchives.gov.uk/doc/open-government-licence/version/2/"
}
],
"DataQualityLevel": 3,
"DateCreated": "2019-12-24T05:23:00Z",
"SubmissionStatusTypeID": 100
},
{
"IsRecentlyVerified": false,
"ID": 48636,
"UUID": "69C483E6-E271-4315-A56F-E3747EA59D52",
"DataProviderID": 1,
"OperatorID": 93,
"OperatorsReference": "SC99",
"UsageTypeID": 4,
"UsageCost": "Free",
"AddressInfo": {
"ID": 48982,
"Title": "Dunsilly Park and Ride, Dunsilly Roundabout",
"AddressLine1": "Dunsilly Park and Ride, Dunsilly Roundabout,",
"Town": "Antrim",
"Postcode": "BT41 2JH",
"CountryID": 1,
"Latitude": 54.74636,
"Longitude": -6.234244,
"Distance": 4.081140533868653,
"DistanceUnit": 2
},
"Connections": [
{
"ID": 60091,
"ConnectionTypeID": 25,
"Reference": "1",
"StatusTypeID": 50,
"LevelID": 2,
"Amps": 32,
"Voltage": 400,
"PowerKW": 22,
"CurrentTypeID": 20,
"Quantity": 2
}
],
With the data struct file:
import Foundation
struct PublicCharger: Decodable {
let AddressInfo: AddressInfo
let Connections: [Connections]
}
struct AddressInfo: Decodable {
let Title: String
let Latitude: Double
let Longitude: Double
}
struct Connections: Decodable {
let StatusTypeID: Int
let ConnectionTypeID: Int
let PowerKW: Int
}
In my View Controller:
let decodedData = try decoder.decode([PublicCharger].self, from: data)
if !decodedData.isEmpty {
//print("Ran")
//print("Data: \(decodedData[0].AddressInfo.Title)")
let count = 0...10
for i in count {
publicChargerTitle.append(decodedData[i].AddressInfo.Title)
publicChargerLatitude.append(decodedData[i].AddressInfo.Latitude)
publicChargerLongitude.append(decodedData[i].AddressInfo.Longitude)
publicChargerStatus1.append(decodedData[i].Connections[0].StatusTypeID)
publicChargerStatus2.append(decodedData[i].Connections[1].StatusTypeID)
publicChargerConnector1.append(decodedData[i].Connections[0].ConnectionTypeID)
publicChargerConnector2.append(decodedData[i].Connections[1].ConnectionTypeID)
publicChargerKW1.append(decodedData[i].Connections[0].PowerKW)
publicChargerKW2.append(decodedData[i].Connections[1].PowerKW)
}
This works and adds the data to its own array.
The issue I'm seeing is not all chargers have the same number of connections. So when parsed the arrays are not matching each other at the end. Instead of skipping that array allocation with the next charger data, is there a way I can instead insert Null into the array to hold its place?
I have looked around and haven't yet found a clear solution to this issue. Any help would be greatly appreciated. API data from: https://api.openchargemap.io/
Thanks
How can I get the data out of this array stored in a variant column in Snowflake. I don't care if it's a new table, a view or a query. There is a second column of type varchar(256) that contains a unique ID.
If you can just help me read the "confirmed" data and the "editorIds" data I can probably take it from there. Many thanks!
Output example would be
UniqueID ConfirmationID EditorID
u3kd9 xxxx-436a-a2d7 nupd
u3kd9 xxxx-436a-a2d7 9l34c
R3nDo xxxx-436a-a3e4 5rnj
yP48a xxxx-436a-a477 jTpz8
yP48a xxxx-436a-a477 nupd
[
{
"confirmed": {
"Confirmation": "Entry ID=xxxx-436a-a2d7-3525158332f0: Confirmed order submitted.",
"ConfirmationID": "xxxx-436a-a2d7-3525158332f0",
"ConfirmedOrders": 1,
"Received": "8/29/2019 4:31:11 PM Central Time"
},
"editorIds": [
"xxsJYgWDENLoX",
"JR9bWcGwbaymm3a8v",
"JxncJrdpeFJeWsTbT"
] ,
"id": "xxxxx5AvGgeSHy8Ms6Ytyc-1",
"messages": [],
"orderJson": {
"EntryID": "xxxxx5AvGgeSHy8Ms6Ytyc-1",
"Orders": [
{
"DropShipFlag": 1,
"FromAddressValue": 1,
"OrderAttributes": [
{
"AttributeUID": 548
},
{
"AttributeUID": 553
},
{
"AttributeUID": 2418
}
],
"OrderItems": [
{
"EditorId": "aC3f5HsJYgWDENLoX",
"ItemAssets": [
{
"AssetPath": "https://xxxx573043eac521.png",
"DP2NodeID": "10000",
"ImageHash": "000000000000000FFFFFFFFFFFFFFFFF",
"ImageRotation": 0,
"OffsetX": 50,
"OffsetY": 50,
"PrintedFileName": "aC3f5HsJYgWDENLoX-10000",
"X": 50,
"Y": 52.03909266409266,
"ZoomX": 100,
"ZoomY": 93.75
}
],
"ItemAttributes": [
{
"AttributeUID": 2105
},
{
"AttributeUID": 125
}
],
"ItemBookAttribute": null,
"ProductUID": 52,
"Quantity": 1
}
],
"SendNotificationEmailToAccount": true,
"SequenceNumber": 1,
"ShipToAddress": {
"Addr1": "Addr1",
"Addr2": "0",
"City": "City",
"Country": "US",
"Name": "Name",
"State": "ST",
"Zip": "00000"
}
}
]
},
"orderNumber": null,
"status": "order_placed",
"submitted": {
"Account": "350000",
"ConfirmationID": "xxxxx-436a-a2d7-3525158332f0",
"EntryID": "xxxxx-5AvGgeSHy8Ms6Ytyc-1",
"Key": "D83590AFF0CC0000B54B",
"NumberOfOrders": 1,
"Orders": [
{
"LineItems": [],
"Note": "",
"Products": [
{
"Price": "00.30",
"ProductDescription": "xxxxxint 8x10",
"Quantity": 1
},
{
"Price": "00.40",
"ProductDescription": "xxxxxut Black 8x10",
"Quantity": 1
},
{
"Price": "00.50",
"ProductDescription": "xxxxx"
},
{
"Price": "00.50",
"ProductDescription": "xxxscount",
"Quantity": 1
}
],
"SequenceNumber": "1",
"SubTotal": "00.70",
"Tax": "1.01",
"Total": "00.71"
}
],
"Received": "8/29/2019 4:31:10 PM Central Time"
},
"tracking": null,
"updatedOn": 1.598736670503000e+12
}
]
So, this is how I'd query that exact JSON assuming the data is in column var in table x:
SELECT x.var[0]:confirmed:ConfirmationID::varchar as ConfirmationID,
f.value::varchar as EditorID
FROM x,
LATERAL FLATTEN(input => var[0]:editorIds) f
;
Since your sample output doesn't match the JSON that you provided, I will assume that this is what you need.
Also, as a note, your JSON includes outer [ ] which indicates that the entire JSON string is inside an array. This is the reason for var[0] in my query. If you have multiple records inside that array, then you should remove that. In general, you should exclude those and instead load each record into the table separately. I wasn't sure whether you could make that change, so I just wanted to make note.
I've a table in postgres named: op_user_event_data, which has a column named data, where I store a jsonb, and what I have at the moment is a json like this:
{
"aisles": [],
"taskGroups": [
{
"index": 0,
"tasks": [
{
"index": 1,
"mandatory": false,
"name": "Dados de Linear",
"structuresType": null,
"lines": [
{
"sku": {
"skuId": 1,
"skuName": "Limiano Bola",
"marketId": [
1,
3,
10,
17
],
"productId": 15,
"brandId": [
38,
44
]
},
"taskLineFields": [
{
"tcv": {
"value": "2126474"
},
"columnType": "skuLocalCode",
"columnId": 99
},
{
"tcv": {
"value": null
},
"columnType": "face",
"columnId": 29
},
]
},
{
"sku": {
"skuId": 3,
"skuName": "Limiano Bolinha",
"marketId": [
1,
3,
10,
17
],
"productId": 15,
"brandId": [
38,
44
]
},
"taskLineFields": [
{
"tcv": {
"value": "2545842"
},
"columnType": "skuLocalCode",
"columnId": 99
},
{
"tcv": {
"value": null
},
"columnType": "face",
"columnId": 29
},
]
},
{
"sku": {
"skuId": 5,
"skuName": "Limiano Bola 1/2",
"marketId": [
1,
3,
10,
17
],
"productId": 15,
"brandId": [
38,
44
]
},
"taskLineFields": [
{
"tcv": {
"value": "5127450"
},
"columnType": "skuLocalCode",
"columnId": 99
},
{
"tcv": {
"value": "5.89"
},
"columnType": "rsp",
"columnId": 33
}
]
}
Basically I've an object which has
Aisles [],
taskGroups,
id and name.
Inside the taskGroups as shown in the json, one of the atributes is tasks which is an array, that also have an array called lines which have an array of sku and tasklines.
Basically:
taskGroups -> tasks -> lines -> sku or taskLineFields.
I've tried different queries to get the sku but when I try to get anything further than 'lines' it just came as blank or in some other tries 'cannot call elements from scalar'
Can anyone help me with this issue? Note this is just a sample json.
Anyone knows how make this to work:
I Want all lines where lines->taskLineFields->columnType = 'offer'
All I can do is this, but throwing error on scalar:
SELECT lines->'sku' Produto, lines->'taskLineFields'->'tcv'->>'value' ValorOferta
FROM sd_bel.op_user_event_data,
jsonb_array_elements(data->'taskGroups') taskgroups,
jsonb_array_elements(taskgroups->'tasks') tasks,
jsonb_array_elements(tasks->'columns') columns,
jsonb_array_elements(tasks->'lines') lines
WHERE created_by = 'belteste'
AND lines->'taskLineFields'->>'columnType' = 'offer'
say your data is in some json_column in your table
with t as (
select json_column as xyz from table
),
tg as ( select json_array_elements(xyz->'taskGroups') taskgroups from t),
tsk as (select json_array_elements(taskgroups->'tasks') tasks from tg)
select json_array_elements(tasks->'lines') -> 'sku' as sku from tsk;