API JSON formatting to bootstrap-vue table - javascript

I am a student working on a VueJS dashboard displaying scientific research data from clinicaltrials.gov. The issue is the JSON response value is in the form of an array and as such prints with brackets and quotation marks in the table. I am trying to display the data without the brackets and quotations. In addition, when there are multiple items as in the Condition field, I am trying to display each item seperated by commas.
The data comes from the API as an axios response in the following format:
{
"StudyFieldsResponse":{
"APIVrs":"1.01.02",
"DataVrs":"2021:03:18 22:20:36.369",
"Expression":"Pfizer",
"NStudiesAvail":371426,
"NStudiesFound":5523,
"MinRank":1,
"MaxRank":1,
"NStudiesReturned":1,
"FieldList":[
"OrgFullName",
"Acronym",
"InterventionName",
"Condition",
"Phase",
"LastKnownStatus",
"ResultsFirstPostDate",
"LastUpdatePostDate"
],
"StudyFields":[
{
"Rank":1,
"OrgFullName":[
"Pfizer"
],
"Acronym":[],
"InterventionName":[
"Infliximab [infliximab biosimilar 3]"
],
"Condition":[
"Crohn's Disease",
"Ulcerative Colitis"
],
"Phase":[],
"LastKnownStatus":[],
"ResultsFirstPostDate":[],
"LastUpdatePostDate":[
"December 21, 2020"
]
}
]
}
}
Axios Call in mounted:
var APIurl = "https://clinicaltrials.gov/api/query/study_fields?expr=" + TrialSearch + "%0D%0A&fields=OrgFullName%2CAcronym%2CInterventionName%2CCondition%2CPhase%2CLastKnownStatus%2CResultsFirstPostDate%2CLastUpdatePostDate&min_rnk=1&max_rnk=999&fmt=json"
axios
.get(APIurl)
.then(response => {this.items = response.data.StudyFieldsResponse.StudyFields})
.catch(function (error) {
//eslint-disable-next-line no-console
console.log(error);
})
HTML of b-table:
<b-table :items="items" id="table-list" responsive :per-page="perPage" :current-page="currentPage" :fields="fields" :sort-by.sync="sortBy" :sort-desc.sync="sortDesc" >
</b-table>
js data function:
data: function() {
return {
sortBy: 'name',
perPage: 10,
PipeperPage: 5,
currentPage: 1,
sortDesc: false,
sortByFormatted: true,
filterByFormatted: true,
sortable: true,
fields: [
{ key: 'Acronym', sortable: true },
{ key: 'InterventionName', sortable: true },
{ key: 'Condition', sortable: true },
{ key: 'Phase', sortable: true },
{ key: 'LastKnownStatus', sortable: true },
{ key: 'ResultsFirstPostDate', sortable: true },
{ key: 'LastUpdatePostDate', sortable: true },
],
items: [],
screenshot of current table format
Sorry for the long post; I am really trying to learn but am lost.

Like you said all the properties of the response are arrays instead of primitives values like string, boolean, or number. b-table expects that the items data is an array of rows (that is good) with properties and primitives values like you are passing arrays is printing the whole value as a string.
What you need to do is add a computed property (that will change when items change) mapping that item with a new item, choosing the values you use (to keep it simple) and joining the array in a string.
You can choose to join the array arr.join(', ') or to select the first item arr[0] || "".
Life example https://codesandbox.io/s/api-json-formatting-to-bootstrap-vue-table-r91cw?file=/src/components/Dashboard.vue:1095-1586
<template>
<b-table
:items="simpleItems"
id="table-list"
responsive
:per-page="perPage"
:current-page="currentPage"
:fields="fields"
:sort-by.sync="sortBy"
:sort-desc.sync="sortDesc"
/>
</template>
<script>
export default {
data() {
return {
// your data
}
},
computed: {
simpleItems() {
return this.items.map((item) => {
return {
Acronym: item.Acronym.join(", "),
InterventionName: item.InterventionName.join(", "),
Condition: item.Condition.join(", "),
Phase: item.Phase.join(", "),
LastKnownStatus: item.LastKnownStatus.join(", "),
ResultsFirstPostDate: item.ResultsFirstPostDate.join(", "),
LastUpdatePostDate: item.LastUpdatePostDate.join(", "),
};
})
},
}
}
</script>

Related

VueGoodTable filter dropdown options vue2

I'm trying to populate possible dropdown options on vue good table. The idea is that I conduct an API call to the server to bring back what values can possibly go into the drop down and I'm trying to assign it to the column filter. However, I can't seem to get it to work.
<vue-good-table
:paginationOptions="paginationOptions"
:sort-options="sortOptions"
:isLoading.sync="isTableLoading"
:rows="rows"
:columns="columns"
:lineNumbers="true"
mode="remote"
:totalRows="totalRecords"
#on-row-click="onRowClick"
#on-page-change="onPageChange"
#on-sort-change="onSortChange"
#on-column-filter="onColumnFilter"
#on-per-page-change="onPerPageChange"
#on-search="onSearch"
:search-options="{
enabled: true
}"
styleClass="vgt-table striped bordered"
ref="table"
>
Fairly standard vgt set up.
columns: [
{
label: 'some column',
field: 'column1'
},
{
label: 'Customer',
field: 'customerName',
filterOptions: {
enabled: true,
placeholder: 'All',
filterDropdownItems: Object.values(this.customers)
}
},
{
label: 'other columns',
field: 'column234'
}
]
and the API call
methods: {
async load () {
await this.getTableOptions()
},
async getTableOptions () {
try {
var response = await axios.get(APICallUrl)
this.customers= []
for (var i = 0; i < response.data.customers.length; i++) {
this.customers.push({ value: response.data.customers[i].customerId, text: response.data.customers[i].customerName})
}
} catch (e) {
console.log('e', e)
}
}
The only thing that I thought of is that the table has finished rendering before the load method is complete. However just creating a static object in my data and assigning it to a filterDropDownItems yielded no better results. The result whenever I try to set it to an object is that the box is a type-in box rather than a dropdown.
You can make the table update after it's rendered by making columns a computed property. The other problem you have is this.customers is an Array but Object.values() expects an Object. You could use the Array.map function instead
this.customers.map(c => c.value)
Although according to the VueGoodTable docs an array of objects like you have should work just fine
computed: {
columns() {
return [
{
label: 'some column',
field: 'column1'
},
{
label: 'Customer',
field: 'customerName',
filterOptions: {
enabled: true,
placeholder: 'All',
filterDropdownItems: this.customers
}
},
{
label: 'other columns',
field: 'column234'
}
];
}
}

How to format date in ant table?

I have a table with 6 columns, one of these columns is a date, The default display format of the date is 2020-04-30T21:30:07.000Z I want to change it to 30-04-2020.
export const columns = [
{ title: `ID`, dataIndex: `invoice_id`},
{ title: `Invoice Number`, dataIndex: `invoice_number` },
{ title: `Amount`, dataIndex: `invoice_amount`},
{ title: `Store Name`, dataIndex: `store_name`},
{ title: `Supplier Name`, dataIndex: `supplier_name`},
{ title: `Creation Date`, dataIndex: `invoice_date`,},
]
<Table bordered columns={columns} dataSource={invoices_list} />
I believe there should be a way to pass date format to the columns. I looked into the ant table documentations but didn't find a solution.
Another way to implement it is to define a 'render' for a date column like
{
title: 'Published at',
dataIndex: 'publishedAt',
key: 'publishedAt',
width: 210,
render: ((date:string) => getFullDate(date)) }
and just utilize date formatting function getFullDate. In your case it can look like
export const getFullDate = (date: string): string => {
const dateAndTime = date.split('T');
return dateAndTime[0].split('-').reverse().join('-');
};
In this case you'll also avoid using external libraries and will have a function to format the date in other places.
After looking into the antd documentation (https://ant.design/components/table/#API) it doesn't seems to have a property to handle your case. You should duplicate your column invoices_date to invoices_date_printabble which will have the good format to be printed.
invoices_list.map(el => {
let date = new Date(el.invoices_date)
el.invoices_date_printabble = date.getDay()+"/"+date.getMonth()+"/"+date.getFullYear()
})
And now your list is printable.
export const columns = [
{ title: `ID`, dataIndex: `invoice_id`},
{ title: `Invoice Number`, dataIndex: `invoice_number` },
{ title: `Amount`, dataIndex: `invoice_amount`},
{ title: `Store Name`, dataIndex: `store_name`},
{ title: `Supplier Name`, dataIndex: `supplier_name`},
{ title: `Creation Date`, dataIndex: `invoices_date_printabble`},
]
<Table bordered columns={columns} dataSource={invoices_list} />
Another way to do it using moment.js library.
First install moment.js into your project
npm i moment
Second import it to your component
import moment from 'moment';
Third change date format:
let invoices=response.data
invoices.map(el => {
let date = moment(new Date(el.invoice_date));
el.invoice_date = date.format("DD/MM/YYYY")
})
this worked for me!
export const columns = [
{
title: "ID",
key: "key",
render: (record) => {
return (
<div>
<p>{moment(record.invoice_id).format("DD-MM-YYYY")}</p>
</div>
);
},
},
]
I think the easiest way would be to use moment.js in the render method of the column options:
Your moment format of your existing date can be found in the moment documentation.
For future reference you can always use a millisecond timestamp and convert to whatever date format you want with moment.
export const columns = [
....
{ title: "Creation Date",
dataIndex: "invoices_date",
render: (invoice_date) => { return (<p>{moment(invoices_date, **"Moment Format"**).format(DD-MM-YYYY)}</p>)},
]

Dynamic lookup from React's state in material-table

I'm using the material-table component, which I fill with dynamic data coming from Redux (an array of objects), but then I do other things with that data inside my component's state. To create column dropdown filters, there's an element inside each column's array of options, lookup, that receives an object and creates the dropdown based on it's values.
I am extracting some items from my data and putting them inside an element in my component's state. This is an object, the same kind that lookup receives. The thing is that the component shows an empty dropdown, as if the object was empty, but it's not. I'm logging it in into the console and the object is filled with the data I need.
I initially thought it was a render problem, that the object is empty at the beggining, and then it's filled with data, but the component renders every time.(Yeah, React is reactive).
This is only the code needed to help me solve this problem:
Table component
import React, { Component } from "react";
import MaterialTable from "material-table";
class CustomTable extends Component {
state = {
column1: "",
column2: "",
column3: "",
column1FilterList: {}
columns: [
{
title: "Column1",
field: "column1",
editable: "onAdd",
filtering: true,
lookup: { ...this.column1FilterList }
},
{
title: "Column2",
field: "column2",
editable: "onAdd",
filtering: true,
},
{
title: "Column3",
field: "column3",
editable: "onAdd",
filtering: true
}
]
};
componentDidMount() {
this.props.fetchValues()
this.props.fetchApplications()
this.filterColumn1ExistingKeys()
}
filterColumn1ExistingKeys = () => {
return this.props.elements.map(element => {
return this.setState(prevState => ({
column1FilterList: {
...prevState.column1FilterList,
[element.name]: element.name
}
}))
})
}
render() {
return (
<div>
<MaterialTable
options={{
search: false,
actionsColumnIndex: 4,
filtering: true
}}
title="Search by"
columns={this.state.columns}
data={this.state.data}
/>
</div>
);
}
}
export default CustomTable;
The problem is how you save that data. You create a new object in the constructor with { ...this.column1FilterList }. This will create a new object which will act as the lookup object, which is filled with the initial data of column1FilterList (empty). Updating the column1FilterList later does not change that lookup object, because it is disconnected (new object). You have to update the lookup within the columns as well like this:
const filterColumn1ExistingKeys = () => {
const column1FilterList = this.state.column1FilterList;
this.props.elements.forEach(element => column1FilterList[element.name] = element.name)
this.setState({
column1FilterList,
columns: [{
title: "Column1",
field: "column1",
editable: "onAdd",
filtering: true,
lookup: { ...column1FilterList }
},
{
title: "Column2",
field: "column2",
editable: "onAdd",
filtering: true,
},
{
title: "Column3",
field: "column3",
editable: "onAdd",
filtering: true
}
]
})
}
Hope this helps. Let me know, if that works for you. If you have any questions, let me know. Happy coding.

Send more values via URL

I am using Datatable plug-in to print values from database.
I get results and it prints in table. Now I am having trouble with sending values to the other file. Values that I need to send are userID, all titles of column except for last title, and two other variables which contains date.
When I click on '', beside data that contains userId, I need to send "User, Work time, Additions, Business, Break" as well as two variables printed below.
Other two variables are:
var date1 = "2017-01-01";
var date2 = "2017-02-28";
$('#myData').DataTable( {
data: dataSet,
fixedHeader: true,
responsive: true,
"columns": [
{ title: "User", data: "ime"},
{ title: "Work time", data: "Rad" },
{ title: "Additions", data: "Privatno" },
{ title: "Business", data: "Poslovno" },
{ title: "Break", data: "Pauza" },
{
"title": '<i class="icon-file-plus"></i>',
"data": "userID",
"render": function (data) {
return '' + '<i class="icon-file-plus"></i>' + '';
}, "width": "1%",
}
]
,"columnDefs": [ { "defaultContent": "-", "targets": "_all" },{ className: "dt-body-center", "targets": [ 5 ] } ]
});
Any help or advice is appreciated, I am stuck here.

Store calculated data in Column of Kendo Grid

What I'm trying to do is store some data in a specific column that is calculated by using the data from another column.
I currently have a function that returns the number of available licenses for the given Id in JSON
function getAvailableLicenses(id) {
var url = "/Host/Organization/AvailableLicenses/" + id;
$.get(url, function (data) {
return data.AvailableLicenses;
});
}
How do I go about storing this number in a column named "AvailableLicenses"?
Here is my current Grid:
$("#OrganizationGrid").kendoGrid({
dataSource: viewModel.get("orgDataSource"),
filterable: {
extra: false
},
sortable: true,
pageable: true,
columns: [
{ field: "Id", hidden: true },
{ field: "Name", template: "<a href='/Host/Organization/Detail/#:Id#'>#:Name#</a>" },
{ field: "LicenseNumber", title: "Number of Licenses" },
{ field: null, title: "Available Licenses", template: "#= getAvailableLicenses(Id) #" },
{ field: "LicenseExpiration", title: "License Expiration", format: "{0:MM/dd/yyyy}" },
{ field: "State" },
{ field: "Active" }
],
editable: false
});
As you can see, I tried to create a null column with a template that calls the function for the given Id.
By using Fiddler I can see that the function is indeed being called for all of the rows, but the AvailableLicenses column just displays Undefined for every row.
Is there something I'm missing here to get this to work?
I think the better way to do this is on dataSource parse() function
First: you column configuration must change like this:
{ field: "AvalableLicenses", title: "Available Licenses" },
You alaways can use you template .
And second, inside your dataSource() you can add:
schema: {
parse: function(response) {
for (var i = 0; i < response.length; i++) {
response[i].AvalableLicenses= null;
response[i].AvalableLicenses = getAvailableLicenses(response[i].Id)
}
return response;
}
}
EDIT:
If you prefer using you way, I dont see any problem in your configuration, probably your $.get is returning undefined, or something you don't expect.
For conviniance I did an example working.
http://jsfiddle.net/jwocf897/
Hope this help

Categories

Resources