Replace string in int - vuejs2

I have a simple question but I don't know how to solve it.
This is my code:
for (var i = 0; i < response.data.values.length; i++) {
this.affinityZone.push({
'text': response.data.values[i].name,
**'value': response.data.values[i].id**
})
}
The 'value' is a string now. So how can my frontend read it as integer.
I tried: 'value': parseInt == response.data.values[i].id and 'value': parseInt.response.data.values[i].id.

Perhaps you're trying to do something like this
for (var i = 0; i < response.data.values.length; i++) {
this.affinityZone.push({
text: response.data.values[i].name,
value: parseInt(response.data.values[i].id, 10)
})
}

This is the answer:
'value': Number.parseInt(response.data.values[i].id)
I should insert Number to parseInt.
Thank you all.

Related

Material-table lookup does not work with a dynamically constructed variable

I am passing a variable constructed as the following code for Lookup.
let classLookup = {};
let classOptions = responseData.classOptions;
for (var i = 0; i < classOptions.length; ++i) {
classLookup[i] = classOptions[i];
}
Here responseData.classOptions is an array:
[{0: "A"}, {1:"B"}....]
classLookup is then constructed as:
{0: "A", 1: "B" ....}
Passing classLookup to material-table does not get recognized.
{
title: 'Class',
field: 'Class',
lookup: classLookup
},
However, if I hard coded classLookup as
let classLookup = {0: "A", 1: "B" ....}
It works fine.
I am clueless what was wrong with the variable I constructed. Please help. Thanks in advance.
Issue found. I shall use useState to set classLookup.
const [classLookup, setClassLookup] = useState();
let tmp = {};
let classOptions = responseData.classOptions;
for (var i = 0; i < classOptions.length; ++i) {
tmp[i] = classOptions[i];
}
setClassLookup(tmp)

Dom-repeat not re-rendering when Array sorts

I have an array property:
arrayList: {
type: Array,
value:[
{id:"1",candy:"Reeces"},
{id:"1",candy:"M&M"},
{id:"1",candy:"KitKat"},
{id:"1",candy:"Twizzlers"}
]
}
and a boolean property
forceRerender: {
type: Boolean,
value: false
}
I call them in a Dom-Repeat to populate the HTML:
<template is="dom-repeat" as="candy" items="[[getCandyList(arrayList, forceRerender)]]">
<div id="[[candy.id]]" class="candy-row" data="[[candy]]" on-tap="selectCandy">
</template>
The selectCandy() function looks like this:
selectCandy(event) {
let arr = this.arrayList;
for(let j = 0, i = 0; j < arr.length; j++) {
if(arr[j].select) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
}
}
this.set('forceRerender', !this.forceRerender);
}
And my getter:
getCandyList(arr,forceRerender) {
return arr;
}
My selectCandy() effectively rearranges the arrayList, but does not visually update the HTML content to represent this. I can't seem to figure out why.
I've made a separate array and used that to change values. I've made a local array and pushed to that and returned it. I've rewritten the order in which things are done. Separated the sections up multiple times to review each portion individually.
I've been at this for at least 3 hours and I'm lost. Can't anyone explain to me here what I'm doing wrong?
This below example could give you some inspiration. As far as I understood, you want to move up (top) the selected item.
Demo
<template is="dom-repeat" items="[[getCandyList(arrayList, forceRerender)]]" as="candy">
<paper-item on-tap="selectCandy"> <div id="[[candy.id]]" class="candy-row" data="[[candy]]"> [[candy.id]] - [[candy.candy]]</div>
</paper-item>
</template>
And the Js may look like:
selectCandy(e) {
let temp = this.arrayList;
//In order to observable change in dom-repeat
this.set('arrayList', []);
temp.splice(e.model.index, 1);
temp.unshift(e.model.candy);
this.set("arrayList", temp);
this.set('forceRerender', !this.forceRerender);
}
You may re-organize the array with other types.
I have discovered the solution:
getCandyList(arr,forceRerender) {
let rowList = [];
for(let j = 0, i = 0; j < arr.length; j++) {
if(arr[j].select) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
}
}
arr.forEach(function(object) {
rowList.push(object);
}.bind(this));
return rowList;
}
and
selectCandy(event) {
this.set('forceRerender', !this.forceRerender);
}
moral of the story here is do all the stuff you wanna do to your objects and arrays in the get function.

Reading from an object

I want to retrieve the values of marked dates how can I get all the marked dates where marked value is true from this object:
alert(JSON.stringify(this.state._markedDates))
{"2018-09-26":{"marked":true}, "2018-09-27":{"marked":false}, "2018-09-29":{"marked":true}}
Expected Result :
{"2018-09-26","2018-09-29"}
I tried the following but datelist is still empty:
for(var i=0; i<this.state._markedDates.length ; i++)
{
if(this.state._markedDates[i].marked == true)
{
this.state.datesList.push(_markedDates[i])
}
}
let dates = {
"2018-09-26":{"marked":true},
"2018-09-27":{"marked":false},
"2018-09-29":{"marked":true}
}
let markedDates=[];
Object.keys(dates).map(date => {
if(dates[date].marked){ markedDates.push(date)}
})
console.log(markedDates)
There are different ways of approaching this, you could filter them for example as below:
let dates = ["2018-09-26":{"marked":true}, "2018-09-27":{"marked":false}, "2018-09-29":{"marked":true}];
let filtered = dates.filter( date => {
if(date.marked === true) {
return date;
}
});
// filtered = {"2018-09-26":{"marked":true}, "2018-09-29":{"marked":true}};
This is how you can get all of the dates where marked = true.
Then you can do
let keyNames = Object.keys(filtered);
console.log(keyNames); // Outputs ["2018-09-26","2018-09-29"]
As a for loop
let markedDates = [];
for(var i=0; i<this.state._markedDates.length; i++)
{
if(this.state._markedDates[i].marked === true)
{
markedDates.push(_markedDates[i])
}
}
this.setState({ObjectIWantToSet: markedDates})
let dates = []
let obj = {"2018-09-26":{"marked":true}, "2018-09-27":{"marked":false}, "2018-09-29":{"marked":true}}
for(date in obj)
{
if(a[date]["marked"])
{
dates.push(date)
}
}
console.log(dates)

Pivot data dynamically for google line chart

I want to display "population" of various countries through the years in the same line chart. The data displayed is based on selections from a multi-select dropdown "Countries". Underlying Data Table has 3 columns:
Year, Country, Population
2012,countryA,33
2013,countryA,35
2014,countryA,40
2012,countryB,65
2013,countryB,70
2014,countryB,75
2012,countryC,15
2013,countryC,20
2014,countryC,25
I am trying to create a pivoted Data View from the underlying Data Table
The code I am using is:
function drawLineChart() {
var arr = $('#country').val();
var lineChartJson = $.ajax({
url: "../json/lineChart.json",
dataType: "json",
async: false
}).responseText;
var lineChartData = new google.visualization.DataTable(lineChartJson);
var view = new google.visualization.DataView(lineChartData);
var viewCols = [0];
for(var i = 0; i < arr.length; i++) {
var viewCols1 = [{
type: 'number',
label: arr[i],
calc: function (dt, row) {
return (dt.getValue(row, 1) == arr[i]) ? dt.getValue(row, 2) : null;
}
}];
viewCols = viewCols.concat(viewCols1);
}
view.setColumns(viewCols);
var aggCols = [{
column: 1,
type: 'number',
label: view.getColumnLabel(1),
aggregation: google.visualization.data.sum
}];
for(var i = 2; i < 4; i++) {
var aggCols1 = [{
column: i,
type: 'number',
label: view.getColumnLabel(i),
aggregation: google.visualization.data.sum
}];
aggCols = aggCols.concat(aggCols1);
}
var pivotedData = google.visualization.data.group(view, [0], aggCols);
But this does not seem to work as expected and I just get 1 Line in the chart with values for all countries added up (although I can see the legend for 3 countries)
On the other hand if I set my View columns as below, it works as expected.
view.setColumns([0, {
type: 'number',
label: arr[0],
calc: function (dt, row) {
return (dt.getValue(row, 1) == arr[0]) ? dt.getValue(row, 2) : null;
}
}, {
type: 'number',
label: arr[1],
calc: function (dt, row) {
// return values of C only for the rows where B = "bar"
return (dt.getValue(row, 1) == arr[1]) ? dt.getValue(row, 2) : null;
}
}, {
type: 'number',
label: arr[2],
calc: function (dt, row) {
return (dt.getValue(row, 1) == arr[2]) ? dt.getValue(row, 2) : null;
}
}]);
What is going wrong in the loop? Is something wrong with "concat" in the loop where I am creating View Columns? I also saw the viewCols array by using console.log and it seems to have the right elements
I was trying to follow the below post:
Creating pivoted DataView from existing google charts DataTable object
the problem has to do with scope
arr[i] is undefined within calc: function (dt, row)
here is another way to pivot the data...
google.charts.load('current', {
callback: function () {
var arr = [
'countryA',
'countryB',
'countryC'
];
var lineChartData = google.visualization.arrayToDataTable([
['Year', 'Country', 'Population'],
[2012,'countryA',33],
[2013,'countryA',35],
[2014,'countryA',40],
[2012,'countryB',65],
[2013,'countryB',70],
[2014,'countryB',75],
[2012,'countryC',15],
[2013,'countryC',20],
[2014,'countryC',25]
]);
// sort by year
lineChartData.sort([{column: 0}]);
// get unique countries
var countryGroup = google.visualization.data.group(
lineChartData,
[1]
);
// build country data table
var countryData = new google.visualization.DataTable({
cols: [
{label: 'Year', type: 'number'},
]
});
// add column for each country
for (var i = 0; i < countryGroup.getNumberOfRows(); i++) {
countryData.addColumn(
{label: countryGroup.getValue(i, 0), type: 'number'}
);
}
// add row for each year / country
var rowYear;
var rowIndex;
for (var i = 0; i < lineChartData.getNumberOfRows(); i++) {
if (rowYear !== lineChartData.getValue(i, 0)) {
rowYear = lineChartData.getValue(i, 0);
rowIndex = countryData.addRow();
countryData.setValue(rowIndex, 0, rowYear);
}
for (var x = 1; x < countryData.getNumberOfColumns(); x++) {
if (countryData.getColumnLabel(x) === lineChartData.getValue(i, 1)) {
countryData.setValue(rowIndex, x, lineChartData.getValue(i, 2));
}
}
}
// draw agg table
new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'table-div',
dataTable: countryData
}).draw();
// draw line chart
new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart-div',
dataTable: countryData
}).draw();
},
packages: ['corechart', 'table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table-div"></div>
<div id="chart-div"></div>
I could figure out the problem with my code above.
"calc" is the callback function in loop. So only last value of loop variable "i" is visible within the loop.
Putting a wrapper function fixes it:
for(var i = 0; i <= arr.length; i++)(function(i) {
var viewCols1 = [{
type: 'number',
label: arr[i],
calc: function (dt, row) {
return (dt.getValue(row, 1) == arr[i]) ? dt.getValue(row, 2) : null;
}
}];
viewCols = viewCols.concat(viewCols1);
})(i);

Adding Columns Dynamically to SlickGrid with AJAX. Columns don't show up

Using SlickGrid to display some pretty elaborate grids. The Example I am showing here isn't my code but basically an example given by the SlickGrid people duplicating my issue. My Grids need to have columns added dynamically with the column names being fed through an AJAX feed. Creating the column object in JS is not a problem and even adding them using the .push is seems to work fine as I can see them in the firebug console. The new columns never seem to rendner. I get a a bunch of tiny empty cells at the end of the grid but they never populate.
The script below can be replaced with the script in the "example1-simple.html" viewed here.
<script src="../lib/jquery.jsonp-1.1.0.min.js"></script>
<script>
var grid;
var data = [];
var columns = [
{id:"title", name:"Title", field:"title"},
{id:"duration", name:"Duration", field:"duration"},
{id:"%", name:"% Complete", field:"percentComplete"},
{id:"start", name:"Start", field:"start"},
{id:"finish", name:"Finish", field:"finish"},
{id:"effort-driven", name:"Effort Driven", field:"effortDriven"}
];
var dynamicColumns = [];
var options = {
enableCellNavigation: true,
enableColumnReorder: false
};
$(function() {
data = [];
BuildExtraColumnsAJAX();
for (var i = 0; i < 2000; i++) {
data[i] = {
title: "Task " + i,
duration: "5 days",
percentComplete: Math.round(Math.random() * 100),
start: "01/01/2009",
finish: "01/05/2009",
effortDriven: (i % 5 == 0)
};
for (var x = 0; x < 20; x++) {
var columnName = "dynamicColumn" + x;
data[i][columnName] = x;
}
}
//alert("Go Pack Go");
grid = new Slick.Grid("#myGrid", data, dynamicColumns, options);
$("#myGrid").show();
})
function BuildExtraColumnsAJAX(){
//dynamicColumns = [];
for (var x = 0; x < columns.length; x++){
dynamicColumns.push(columns[x]);
}
var url = "http://services.digg.com/search/stories? query=apple&callback=C&offset=0&count=20&appkey=http://slickgrid.googlecode.com&type=javascript";
$.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
alert("BOOM Goes my world");
}
});
}
function onSuccess(resp) {
for (var i = 0; i < resp.stories.length; i++) {
dynamicColumns.push( {
id: "dynamicColumn" + i,
name: "Dynamic Column" + i,
field: "dynamicColumn" + i
});
}
}
function BuildExtraColumns(){
dynamicColumns = [];
for (var x = 0; x < columns.length; x++){
dynamicColumns.push(columns[x]);
}
for (var i = 0; i < 20; i++) {
dynamicColumns.push( {
id: "dynamicColumn" + i,
name: "Dynamic Column" + i,
field: "dynamicColumn" + i
});
}
}
If I put the line grid = new Slick.Grid("#myGrid", data, dynamicColumns, options); in the firebug console and run it the grid than renders fine. It is almost like the script is still executing lines of code even though its not done creating the dynamicColumns.
The Digg AJAX call is just to similute an AJAX call, I of course would be using my own.
The grid is getting initialized before the AJAX call to get the additional columns completes.
Either wait until the columns have loaded to initialize the grid, or update the grid after the additional columns have loaded:
grid.setColumns(dynamicColumns);