I'm using api to get the response array, I'm trying to map the "id" under the "quiz_records" array but it returns undefined. I think that my code are correct.
This is my attempt.
array
"quizRemarks": [
{
"id": 160,
"user_id": 1,
"quiz_id": 18,
"module_id": 29,
"number_of_correct_answers": 2,
"created_at": "2021-10-15T03:52:52.000000Z",
"updated_at": "2021-10-15T03:52:52.000000Z",
"time_started": null,
"time_finished": null,
"remarks": 1,
"quiz_records": [
{
"id": 27,
"user_scores_id": 160,
"question_id": 2,
"user_answers": "DriverPH",
"remarks_correct_incorrect": "1",
"created_at": null,
"updated_at": null,
"question_text": "What is the name of this application?"
},
{
"id": 28,
"user_scores_id": 160,
"question_id": 2,
"user_answers": "Red",
"remarks_correct_incorrect": "1",
"created_at": null,
"updated_at": null,
"question_text": "What traffic light color tells you to stop before the intersection?"
}
]
}
]
ts
this.quiz_records = res['quizRemarks'].map(res => res['quiz_records'].id);
console.log(this.quiz_records);
quizRemarks is an array of objects containing an array of quiz_records. Try this to get a flat list of ids of quiz_records:
this.quiz_records = [];
this.quizRemarks.forEach(remark => {
this.quiz_records.push(...remark.quiz_records.map(rec => rec.id));
});
Below code will work----
this.quiz_records = res['quizRemarks'].map(res => res['quiz_records'].map(r => r.id));
You're truing to get an id property from an array, what it inpossible.
You can use nested map + flat() array method.
const result = res['quizRemarks'].map(remarks => {
return remarks['quiz_records'].map(record => record.id);
}).flat();
Related
I have an arrayof objects like
[
null,
{
"list_type": 1,
"list_item": {
"id": 21,
"name":"aaa"
}
},
null,
null,
{
"list_type": 0,
"list_item": {
"id": 24,
"name":"bbb"
}
}
]
I want to remove the null values from this. I have used array_filter() but it doesn't work.
How can I achieve this?
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 want to group the data based on the type and type_id
Here is the array
var addArray = [
{
"id": 24,
"language_id": 3,
"type": "service",
"type_id": 2,
"key": "service seeker",
"value": " need service"
},
{
"id": 23,
"language_id": 3,
"type": "service",
"type_id": 2,
"key": "phone",
"value": "phone number"
},
{
"id": 24,
"language_id": 3,
"type": "service",
"type_id": 7,
"key": "tester",
"value": "service tester"
}
{
"id": 19,
"language_id": 3,
"type": "offer",
"type_id": 4,
"key": "source",
"value": "resource"
}
]
I have tried let result = _.groupBy(addArray,'type') it is grouping the data based on type but I need to group by type as well as type_id
Expected output
If you need the a flat grouping based on two or more properties, use the _.groupBy() callback to combine the properties to a string:
const addArray = [{"id":24,"language_id":3,"type":"service","type_id":2,"key":"service seeker","value":" need service"},{"id":23,"language_id":3,"type":"service","type_id":2,"key":"phone","value":"phone number"},{"id":24,"language_id":3,"type":"service","type_id":7,"key":"tester","value":"service tester"},{"id":19,"language_id":3,"type":"offer","type_id":4,"key":"source","value":"resource"}]
const result = _.groupBy(addArray, o => `${o.type}-${o.type_id}`)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
If you need a multi level grouping, start by grouping by the type, then map the groups with _.values(), and group them again by type_id:
const { flow, partialRight: pr, groupBy, mapValues } = _
const fn = flow(
pr(groupBy, 'type'),
pr(mapValues, g => groupBy(g, 'type_id'))
)
const addArray = [{"id":24,"language_id":3,"type":"service","type_id":2,"key":"service seeker","value":" need service"},{"id":23,"language_id":3,"type":"service","type_id":2,"key":"phone","value":"phone number"},{"id":24,"language_id":3,"type":"service","type_id":7,"key":"tester","value":"service tester"},{"id":19,"language_id":3,"type":"offer","type_id":4,"key":"source","value":"resource"}]
const result = fn(addArray)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
I need to sort my json array in chronological order by it's created_at timestamps.
[{
"id": 1,
"message": "hello",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 12:56:34",
"updated_at": "2015-07-01 12:56:34"
}, {
"id": 2,
"message": "helloWorld",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 12:56:53",
"updated_at": "2015-07-01 12:56:53"
}, {
"id": 3,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 13:12:53",
"updated_at": "2015-07-01 13:12:53"
}, {
"id": 4,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 13:13:04",
"updated_at": "2015-07-01 13:13:04"
}, {
"id": 5,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 15:06:39",
"updated_at": "2015-07-01 15:06:39"
}, {
"id": 1,
"message": "yo yo ",
"investor_id": 35,
"company_id": 7,
"match_id": 2,
"created_at": "2015-07-01 22:09:36",
"updated_at": "-0001-11-30 00:00:00"
}, {
"id": 2,
"message": "sup nigga",
"investor_id": 35,
"company_id": 7,
"match_id": 2,
"created_at": "2015-07-01 14:00:00",
"updated_at": "-0001-11-30 00:00:00"
}]
Can anyone teach me how do i have tried many solutions in stackoverflow . Many of them says array cannot be used with "sortBy" .
This is part of my code :
$companyMessage = Company_Message::where('match_id','=',$match_id);
$investorMessage = Investor_Message::where('match_id','=',$match_id);
$message = array();
if($companyMessage->count()>0 || $investorMessage->count() > 0){
if($lastActivityDate == null ){
//load all messages before
if($companyMessage !=null){
foreach ($companyMessage->get() as $cm) {
array_push($message,$cm);
}
}
if($investorMessage !=null){
foreach($investorMessage->get() as $im){
array_push($message,$im);
}
}
return $message ;
}
I think you can do this using use a laravel database collection api instead of array and add item to collection and use sortBy method on collection,
$col = new \Illuminate\Database\Eloquent\Collection();
if ($companyMessage != null) {
foreach($companyMessage - > get() as $cm) {
$col->add($cm);
}
}
if ($investorMessage != null) {
foreach($investorMessage - > get() as $im) {
$col->add($im);
}
}
$col = $col->sortBy('created_at');
//return the json
return Response::json($jsonArr->toArray());
--- OR ----
Try this but i didn't tested it. If this works then this would be the best way to do this.
$companyMessage = Company_Message::where('match_id','=',$match_id);
$investorMessage = Investor_Message::where('match_id','=',$match_id);
//$companyMessage & $investorMessage both are laravel database collection,
// so you can use merge method on collection to merge these two collections.
$allResults = $companyMessage->merge($investorMessage);
//use laravel collection sort method to sort the collection by created_at
$allResults = $allResults->sortBy('created_at');
//return the json
return Response::json($allResults->toArray());
if($companyMessage !=null){
foreach ($companyMessage->get() as $cm) {
array_push($message,$cm);
}
}
if($investorMessage !=null){
foreach($investorMessage->get() as $im){
array_push($message,$im);
}
}
$message = array_values(array_sort($message, function ($value) {
return $value['created_at'];
}));
Hey man , i found a better solution to sort my array. The answer can be found at laravel docs
http://laravel.com/docs/5.1/helpers#method-array-sort