javascript get string text from json data - javascript

I'm creating a table in react using material UI and trying to figure out how to extract itemlocation from itemInfo and store it in a new column in the table. I know I can do it from the back end, but I can't, and all I want is to be able to extract the string from the item info. I provided an example of how the table and I'll put should look, as well as a snippet of sample code, and I hope this helps because this is how I was thinking of doing it, and I was hoping if anyone knew how I could do it without going into the backend.
simple code
const columns1 = [{
field: "itemInfo",
headerName: "itemInfo",
headeralign: "center",
align: "left",
width: "136",
type: "string",
editable: true,
},
{
field: "itemlocation",
headerName: " itemlocation",
headeralign: "center",
align: "left",
width: "136",
type: "string",
editable: true,
renderCell: (params) => {
return (
<> </>
);
}
},]
Json data
const Rows =[{
"id": "2433-10",
"busiName": "ABC",
"srTypeId": "2433-10",
"nodeType": "0",
"pathName": "home",
"busiSort": 10,
"itemInfo": "1:sql test question: itemlocation=USA",
"superTypeId": "002",}]
Original MUI Table
itemid
itemname
itemInfo
12
car
1:sql test question: itemlocation=USA
99
toy
1:sql test question: itemlocation=USA
I want extract just itemlocation from itemInfo into New table columns
itemid
itemname
itemInfo
itemlocation
12
car
1:sql test question: itemlocation=USA
USA
99
toy
1:sql test question: itemlocation=USA
CHAIN

If you already have access to itemInfo you could run a method similiar to below
const extractLocation = (itemInfo) => {
return itemInfo.match(/itemlocation=(.*)/)[1]
}
This uses regular expression matching to find just the text after itemlocation. If you expect other text that isnt the location to be added to your itemInfo string later on you can update it to exclude that text.
To call this method(assuming your json data is an array of object) you could do.
const location = extractLocation(json[0]['iteminfo'])
// or for all locations
const locations = json.map((item) => {
return extractLocation(item['itemInfo'])
}

let newFormat = items.map(item => {
return {
newProperty: item.oldProperty
}
});

Related

Tabulator: how to modify local array when deleting rows?

I'm trying to build an interactive table that could be modified by the user. In my case, the original dataset is a local array of objects.
Tabulator has the buttonCross option to delete rows, but it only affects the table visuals. How can I make it find the matching object the row presents and delete it from the tabledata array?
Here's the code I'm working with:
let tabledata = [{
animal: "hippo",
color: "grey"
},
{
animal: "puma",
color: "black"
},
{
animal: "flamingo",
color: "pink"
}
];
let table = new Tabulator("#example-table", {
data: tabledata,
layout: "fitDataFill",
addRowPos: "bottom",
reactiveData: true,
headerSort: false,
columns: [ //define the table columns
{
title: "animal",
field: "animal",
editor: "input"
},
{
title: "color",
field: "color",
editor: "input"
},
{
formatter: "buttonCross",
width: 40,
align: "center",
cellClick: function (e, cell) {
cell.getRow().delete();
}
},
],
});
Codepen here.
Would really appreciate some tips on how to make this work!
Working example for tabulator
the filter function is used to remove the current item for the collection
filter Filter API.
First filter the object you don't need and then assign it to tabledata.
cellClick: function (e, cell) {
debugger;
var animalToDelete={ animal:cell.getRow().getData().animal,
color:cell.getRow().getData().color
};
var filtered=tabledata.filter(function(x){
debugger;
return x.animal!=animalToDelete.animal
&& x.color!=animalToDelete.color;
});
tabledata=filtered;
cell.getRow().delete();
}
You could also look to use tabulator in Reactive Data Mode
In this mode it will update the table in real time to match the provided data array as it is changed, and vice versa it will update the array to match the table.
To do this set the reactiveData property to true in the tables constructor object.
//create table and assign data
var table = new Tabulator("#example-table", {
reactiveData:true, //enable reactive data
data:tableData, //assign data array
columns:[
{title:"Name", field:"name"},
{title:"Age", field:"age", align:"left", formatter:"progress"},
{title:"Favourite Color", field:"col"},
{title:"Date Of Birth", field:"dob", sorter:"date", align:"center"},
]
});
It will then maintain a link with the initial data source

Highcharts, build a "Text" graph

I'm using highcharts to build my charts that shows the values that comes from a sensor placed into my garage: all of these values are numeric values, so, i have no problem to build a graph like the following one JSFIDDLE
As i've said, all of the values that comes from the sensor are numeric, except one: the "status", this value is a string value type and it's not a fixed string, it can be:
Transmitting
Standby
Active
Alarm
Or any free string
So, my intention is - and i don't know if that can be feasible - to draw a graph with a fixed serie value (e.g.: 1...maybe i have to use a javascript function that maps the "status" to a given value?) and show that string as fixed datalabels as shown in the fiddle that i've posted.
Final Remarks:
The data that comes from the sensor is a time-series value, like the following:
{"datetime": 1566730095, "status": "transmitting"}
{"datetime": 1566730162, "status": "hello! i'm here"}
This chart will be a separate chart instead the numeric charts, in order to simplify the build and management.
The final goal can be something like that (the following graph is a pure graphical example):
To achieve it you can map data like that:
series: [{
dataLabels: {
enabled: true,
format: '{point.name}',
rotation: -45,
align: 'left',
y: -8
},
data: data.map(item => {
return {
x: item.datetime,
y: 1,
name: item.status
};
})
}]
Demo:
https://jsfiddle.net/BlackLabel/840tv6mz/
To change the way data is exported to CSV you can use this wrapper (edit it as needed):
(function(H) {
H.wrap(H.Chart.prototype, 'getDataRows', function(proceed, multiLevelHeaders) {
var rows = proceed.call(this, multiLevelHeaders);
rows[0][0] = 'Time';
rows[0][1] = 'Status';
rows = rows.map(row => {
if (row.x) {
row[0] = H.dateFormat('%H:%M:%S.%L', row.x);
row[1] = row.name;
}
return row;
});
return rows;
});
}(Highcharts));
Demo:
https://jsfiddle.net/BlackLabel/to92mbu0/

ChartJS dynamically adding values with jQuery array

I am trying to populate a piechart in ChartJS dynamically using data from a jQuery/AJAX query.
The only thing I am struggling with is creating the data in a format that chartJS understands. This is the required format:
var dynamicData = [
{ label: "One", value: 23 },
{ label: "Two", value: 33 },
{ label: "Three", value: 43 },
{ label: "Four", value: 53 },
]
When I try to create it, I get double quotes "" around each set of data. I know it is a simple mistake but I can't figure it out. This is how I am creating the data (partial jQuery code):
.success(function(response) {
if(!response.errors && response.result) {
var doughnutData = [];
$.each(response.result, function( index, value) {
doughnutData.push('{ label: "'+value[0]+'", value: '+value[2]+',color:"#F7464A" }');
});
console.log(doughnutData);
var doughnutOptions = {
segmentShowStroke : true,
segmentStrokeColor : "#fff",
segmentStrokeWidth : 2,
percentageInnerCutout : 50,
animation : true,
animationSteps : 100,
animationEasing : "easeOutBounce",
animateRotate : true,
animateScale : true,
onAnimationComplete : null
}
var ctx = document.getElementById("chart3").getContext("2d");
var mydoughnutChart = new Chart(ctx).Doughnut(dynamicData, doughnutOptions);
} else {
alert("error");
}
The console shows:
["{ label: "17x1p14e6662", value: 16,color:"#F7464A" }", "{ label: "8734hjgfd784ew", value: 8,color:"#F7464A" }"]
What am I doing wrong?
The console is outputting the object as a string because you are pushing a string to the var doughnutData, you are doing this wrapping the object in quotes and concatenating the values to the string therefor treating the argument passed to the push method as a string type.
The proper way to use the push method to add an object to an array would be like this.
array.push({property:'string', property:2})
Meaning your code should look like this.
doughnutData.push({ label:value[0], value:value[2],color:"#F7464A" });
Here is a link on how the push method works on an array and Here is another link to javascript objects
Another thing is when you are creating the chart your are passing the var dynamicData instead of your var doughnutData.

How do you influence position of connectors in a heirarchical Kendo UI Diagram

I am building an organisation chart using Kendo UI's diagramming component
I do not want the user to be able to edit the diagram as it is a read-only representation of positions they have entered previously, however I do want to display the diagram in a particular way.
The layout type I am using is tree with subtype of down. I am using the HeirarchicalDataSource as the dataSource
The default way the diagram is drawn looks like this:
However, my boss needs it to look like this:
So the parent nodes have all child nodes coming from the bottom connector.
I see no way to programmatically influence this. Please help.
Switching editing off is easy, just pass to your options editable: false. To have the layout similar to what you posted, play with two variables: horizontalSeparation, verticalSeparation under layout
http://dojo.telerik.com/uNOVa/2
function createDiagram() {
$("#diagram").kendoDiagram({
editable: false,
dataSource: {
data: diagramNodes(),
schema: {
model: {
children: "items"
}
}
},
layout: {
type: "tree",
subtype: "down",
horizontalSeparation: 60,
verticalSeparation: 40
},
shapeDefaults: {
width: 40,
height: 40
}
});
}
function diagramNodes() {
var root = { name: "0", items: [] };
addNodes(root, [3, 2, 2]);
return [root];
}
function addNodes(root, levels) {
if (levels.length > 0) {
for (var i = 0; i < levels[0]; i++) {
var node = { name: "0", items: [] };
root.items.push(node);
addNodes(node, levels.slice(1));
}
}
}
$(document).ready(function() {
$("#subtype").change(function() {
$("#diagram").getKendoDiagram().layout({
subtype: $(this).val(),
type: "tree",
horizontalSeparation: 30,
verticalSeparation: 20
});
});
});
$(document).ready(createDiagram);
$(document).bind("kendo:skinChange", createDiagram);
There is another type of rendering connections with:
connectionDefaults: {
type: "polyline"
}
You can check it out here: http://dojo.telerik.com/uNOVa/3
You can also fix your connections with an array:
connections
An example is here:
example

Updating Columns Dynamically - Alloy UI

I'm trying to change columns dynamically in my Alloy UI DataTable - depending on what button is selected, columns are changed depending on which data is returned.
My columns get updated, however the actual data is never included in the table. When I don't define any columns both the columns and data are returned - I of course want control of how my columns are displayed and want to set their attributes
Below is my code:
var dataTable = new Y.DataTable({ //Defining Datatable with no columns preset
editEvent: 'dblclick',
plugins: [{
cfg: {
highlightRange: false
}]
});
button.on(
'click', //On Click...
function() {
var category = $(this).attr("id"); //value retrieved from id of button selected
dataSource = new Y.DataSource.IO({source: '/searchMyData
dataSource.sendRequest({
dataType: 'json',
on: {
success: function(e) {
response = e.data.responseText;
setColumnNames(category); //Set the Columns...
data = Y.JSON.parse(response);
dataTable.set('data', data);//Then the Data
dataTable.render('#my-container');
},
failure: function() {
alert(e.error.message);
}
}
});
function setColumnNames(tabName){ //Defining Columns
var columns1 = [
{ key: 'id', label: 'ID', width: '70px' },
{ key: 'name', label: 'Name', width: '70px' }
];
var columns2 = [
{ key: 'id', label: 'ID', width: '70px' },
{ key: 'addr', label: 'Address', width: '70px' }
];
switch (category) {
case "person":
dataTable.set('columns', columns1);
break;
case "address":
dataTable.set('columns', columns2);
break;
default:
console.log('');
}
There's no issue with the data returning from the ajax request, only when it comes to loading it to the table with a new set of columns defined. I've tried the reset() method on both columns and data on each click, but no luck.
It turns out the keys returned from my request were being capitalized and included underscores (just how they're defined in the database) - I've also noticed defining the columns key is case sensitive. If I changed a single character from lower case to upper than the column would not display data.

Categories

Resources