How can I format following json data in c3js? - json

How can i format following json in c3js?.
I want projectcount as y axis,date as x axis and each line for different user.
Please help me to find out this.
{"ProjectList":[{"date":"18-07-2017","projectcount":2,"user":"Salva"},
{"date":"10-07-2017","projectcount":1,"user":"Jaspreet Kaur"},
{"date":"07-07-2017","projectcount":1,"user":"Sukanya Ray"},
{"date":"29-06-2017","projectcount":1,"user":"Asmita Bhurke"},
{"date":"06-08-2017","projectcount":2,"user":"Salman AP Homes"},
{"date":"31-07-2017","projectcount":1,"user":"Alena Sandra"},
{"date":"27-07-2017","projectcount":1,"user":"Salva"},
{"date":"25-07-2017","projectcount":2,"user":"Salva"},
{"date":"21-07-2017","projectcount":1,"user":"Jaspreet Kaur"},
{"date":"21-07-2017","projectcount":2,"user":"Sandeep Ghanekar"}]}

I'll take these three data points to illustrate:
{"date":"31-07-2017","projectcount":1,"user":"Alena Sandra"},
{"date":"27-07-2017","projectcount":1,"user":"Salva"},
{"date":"25-07-2017","projectcount":2,"user":"Salva"},
For every line you want, you make an array starting with line name.
Then you set its data, filling gaps with nulls.
And you have to set timeseries array (starting with "x") from first to last date:
var chart = c3.generate({
data: {
x: 'x',
xFormat: '%d-%m-%Y', // parse format
"columns": [
[
"x",
"25-07-2017",
"26-07-2017",
"27-07-2017",
"28-07-2017",
"29-07-2017",
"30-07-2017",
"31-07-2017"
],
[
"Salva",
2,
null,
1,
null,
null,
null,
null
],
[
"Alena Sandra",
null,
null,
null,
null,
null,
null,
1
]
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%d-%m-%Y' // display format
}
}
},
line: {
connectNull: true
}
});
See in action.

We can format the JSON as per the graph needs.You can creates the graph as follows
var items = {
"ProjectList": [{ "date": "07-18-2017", "projectcount": 2, "user": "Salva" },
{ "date": "07-10-2017", "projectcount": 1, "user": "Jaspreet Kaur" },
{ "date": "07-07-2017", "projectcount": 1, "user": "Sukanya Ray" },
{ "date": "06-29-2017", "projectcount": 5, "user": "Asmita Bhurke" },
{ "date": "08-06-2017", "projectcount": 1, "user": "Salman AP Homes" },
{ "date": "07-31-2017", "projectcount": 3, "user": "Alena Sandra" },
{ "date": "07-27-2017", "projectcount": 4, "user": "Sandeep Ghanekar" },
{ "date": "07-25-2017", "projectcount": 2, "user": "Salva" },
{ "date": "07-21-2017", "projectcount": 6, "user": "Jaspreet Kaur" },
{ "date": "07-04-2017", "projectcount": 5, "user": "Sandeep Ghanekar" },
{ "date": "07-08-2017", "projectcount": 7, "user": "Salva" },
{ "date": "07-21-2017", "projectcount": 2, "user": "Jaspreet Kaur" },
{ "date": "07-21-2017", "projectcount": 2, "user": "Sandeep Ghanekar" }]
}
var persons=[];
var valueToPush = new Array();
var uniqueArray = items.ProjectList.reduce(function (a, d) {
if (a.indexOf(d.date) === -1) {
a.push(""+d.date+"");
}
return a;
}, ['x']);
uniqueArray.sort(function(a, b) {
dateA = new Date(a),
dateB = new Date(b);
return dateA - dateB;
});
var nameArray = items.ProjectList.reduce(function (a, d) {
if (a.indexOf(d.user) === -1) {
a.push(""+d.user+"");
}
return a;
}, []);
valueToPush[0]=uniqueArray;
var i=1;
nameArray.forEach(function(c){
persons=[];
persons.push(""+c+"")
items.ProjectList.forEach(function(b){
if(c===b.user){
persons.push(b.projectcount)
}
else{
persons.push(null)
}
});
valueToPush[i]=persons;
i++;
});
var chart = c3.generate({
data: {
x: 'x',
xFormat: '%d-%m-%Y',
"columns": valueToPush
},
axis: {
x: {
type: 'category',
tick: {
format: '%d-%m-%Y'
}
}
},
line: {
connectNull: true
}
});
Mention JavaScript support Date formats
Try this JSFiddle

Related

Read Nested JSON object in typescript in NestJs

I am new to type script and Nested JSON Object structure. I am using NestJs . Here is my JSON request
{
"recipes": [
{
"recipe_id": 1,
"ingredients": [
{
"ingredient_id": 2,
"quantity": 4,
"unit": "g",
"nutrients": [
{
"nutrient_id": 1,
"quantity": 2,
"unit": "g"
}
]
},
{
"ingredient_id": 3,
"quantity": 4,
"unit": "g",
"nutrients": [
{
"nutrient_id": 2,
"quantity": 2,
"unit": "g"
}
]
}
]
},
{
"recipe_id": 2,
"ingredients": [
{
"ingredient_id": 4,
"quantity": 4,
"unit": "g",
"nutrients": [
{
"nutrient_id": 4,
"quantity": 2,
"unit": "g"
}
]
},
{
"ingredient_id": 5,
"quantity": 4,
"unit": "g",
"nutrients": [
{
"nutrient_id": 5,
"quantity": 2,
"unit": "g"
}
]
}
]
}
]
}
Below is my code to read above json request
public async createMealRecipe(request) {
try{
const ingredientData = request.recipes.flatMap(item => {
return item.ingredients.map(({ingredient_id, quantity, unit}) =>{
return {
recipe_id: item.recipe_id, ingredient_id, quantity, unit
}
})
});
const nutrientData = request.recipes.flatMap(item1 => {
return item1.nutrients.map(({nutrient_id, quantity, unit}) =>{
return {
recipe_id: item1.recipe_id, nutrient_id, quantity, unit
}
})
});
console.log(ingredientData);
console.log(nutrientData);
}catch(e) {
console.log('e', e);
throw e;
}
}
console.log(ingredientData); is working fine, but when i try to log this console.log(nutrientData); i am getting map undefined error . Please correct me. Actually I am new to nestjs / typescript.
EDIT: `So instead of map function is there any possibility to traverse using forEach loop ?`
The issue is that request.recipes.flatMap(item1 => { doesn't give you an object representing a nutrient. item1 in this case is a recipe such as
{
recipe_id: 1,
ingredients: [
{ ingredient_id: 2, quantity: 4, unit: 'g', nutrients: [Array] },
{ ingredient_id: 3, quantity: 4, unit: 'g', nutrients: [Array] }
]
}
which also makes sense because the loop is no different than the one in which you loop over recipes above. If you'd like to loop over the nutrients of each recipe, you need to loop over the item1.ingredients array first. An example of this would be something like the following:
const nutrientData = request.recipes.flatMap(recipe => {
return recipe.ingredients.map(({ ingredient_id, quantity, unit, nutrients }) => {
return nutrients.map(({ nutrient_id, quantity, unit }) => {
return {
recipe_id: recipe.recipe_id, nutrient_id, quantity, unit
};
});
});
});

{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))

Elasticsearch: how to store all json objects dynamically

I'm trying to store all Json objects through elasticsearch.
client.create({
index: 'index',
type: 'type',
id:"1"
body:result[0]
},function (error,response)
{
if (error)
{
console.log('elasticsearch cluster is down!');
}
else
{
console.log('All is well');
}
});
In this result[0] I'm getting my first value of a Json object but I need to store all Json objects dynamically.
The output which i'm getting is:
-> POST http://localhost:9200/index/type/1?op_type=create
{
"Name": "Martin",
"Age": "43",
"Address": "trichy"
}
<- 201
{
"_index": "index",
"_type": "type",
"_id": "1",
"_version": 4,
"created": true
}
But I need an output like this:
-> POST http://localhost:9200/index/type/1?op_type=create
{
"Name": "Martin",
"Age": "43",
"Address": "trichy"
},
{
"Name": "vel",
"Age": "23",
"Address": "chennai"
},
{
"Name": "ajay",
"Age": "23",
"Address": "chennai"
}
<- 201
{
"_index": "index",
"_type": "type",
"_id": "1",
"_version": 4,
"created": true
}
What you need is to use the bulk endpoint in order to send many documents at the same time.
The body contains two rows per document, the first row contains the index, type and id of the document and the document itself is in the next row. Rinse and repeat for each document.
client.bulk({
body: [
// action description
{ index: { _index: 'index', _type: 'type', _id: 1 } },
// the document to index
{ Name: 'Martin', Age: 43, Address: 'trichy' },
{ index: { _index: 'index', _type: 'type', _id: 2 } },
{ Name: 'vel', Age: 23, Address: 'chennai' },
{ index: { _index: 'index', _type: 'type', _id: 3 } },
{ Name: 'ajay', Age: 23, Address: 'chennai' }
]
}, function (err, resp) {
// ...
});
I suspect your result array is the JSON you get from your other question from yesterday. If so, then you can build the bulk body dynamically, like this:
var body = [];
result.forEach(function(row, id) {
body.push({ index: { _index: 'index', _type: 'type', _id: (id+1) } });
body.push(row);
});
Then you can use the body in your bulk call like this:
client.bulk({
body: body
}, function (err, resp) {
// ...
});