I am trying to push data into a variable Data[] but all I have is an example of how to do this hard coded:
var data = [{
id: "1",
name: "Development Life Cycle",
actualStart: Date.UTC(2018, 01, 02),
actualEnd: Date.UTC(2018, 06, 15),
children: [{
id: "1_1",
name: "Planning",
actualStart: Date.UTC(2018, 01, 02),
actualEnd: Date.UTC(2018, 01, 22),
connectTo: "1_2",
connectorType: "finish-start",
progressValue: "75%"
},
// more data goes here
]
}];
I tried with following code but it doesn't seem to work:
ganttdata = [];
// DUMMY DATA
id = 10;
RFInum = 'asfd';
start= 1;
LTIOV = 2;
progressValue = 10;
ganttdata.push("{id:"+id, "parent: null", "name:"+RFInum, "actualStart: Date.UTC("+start+")", "actualEnd: Date.UTC("+LTIOV+")", "progressValue:"+progressValue+"%}");
console.log(ganttdata);
Anyone know how to write this?
You are currently inserting your data as a string and not as an object.
I recreated your approach and inserted your data as an object into the ganttdata array.
Date documentation
var ganttdata = [];
// DUMMY DATA
var id = 10;
var RFInum = 'asfd';
var start = Date.UTC(2021, 12, 31);
var LTIOV = Date.UTC(2021, 12, 31);
var progressValue = 10;
ganttdata.push({
id,
parent: null,
name: RFInum,
actualStart: start,
actualEnd: LTIOV,
progressValue: `${progressValue}%`,
});
console.log(ganttdata);
Or if you want to append some data to an existing object at a specific index:
var data = [{
id: 1,
name: 'test'
}];
console.log('before:', data);
data[0].extend = 'hello World';
data[0].foo = 'bar';
console.log('after:', data);
Related
I have some data like this, an array of objects:
source = [{
day: 1,
deliveries: 16,
hours: 9
}, {
day: 2,
deliveries: 19,
hours: 11
}]
Which I would like to have in this format:
source = (['day', 'deliveries', 'hours'],
['1', '16', '9'],
['2', '19', '11'])
Sort of like a table. I read up a little on mapping arrays and tried this:
const datatable = source.map(d => Array.from(Object.keys(d)))
console.log(datatable)
// [["day", "deliveries", "hours"], ["day", "deliveries", "hours"]]
And this:
const datatable = source.map(d => Array.from(Object.values(d)))
console.log(datatable)
// [[1, 16, 9], [2, 19, 11]]
Each gives me half of what I want.
I tried this:
let datatable = source.map(d => Array.from(Object.keys(d)))
let datatable2 = source.map(d => Array.from(Object.values(d)))
datatable = datatable[1]
let combined = datatable.concat(datatable2);
console.log(combined)
///["day", "deliveries", "hours", [1, 16, 9], [2, 19, 11]]
But even here the column names are not being combined correctly, and this way seems a little messy. How do I have the keys be on top (like column names would be) and the values following them?
Assuming you want source to be an array of arrays (common for table-like structures), get the keys once, then add each row array mapping the object's properties to the key for that index:
const keys = Object.keys(source[0]);
const result = [keys, ...source.map(obj => keys.map(key => obj[key]))];
Live Example:
const source = [{
day: 1,
deliveries: 16,
hours: 9
}, {
day: 2,
deliveries: 19,
hours: 11
}];
const keys = Object.keys(source[0]);
const result = [keys, ...source.map(obj => keys.map(key => obj[key]))];
console.log(result);
.as-console-wrapper {
max-height: 100% !important;
}
Note that this assumes a couple of things:
The source array always has at least one object in it.
The objects in the source array all have the same set of properties.
You want the keys to be in the order in which they appear in the first object in the array. (JavaScript object properties do have a defined order now, but using that order is almost never a good idea, so you might want to do some kind of sort operation on keys.)
You are almost there. Just use [0] to get the first item to get only keys. And then combine the array using ....
let source = [{
day: 1,
deliveries: 16,
hours: 9
}, {
day: 2,
deliveries: 19,
hours: 11
}]
let ansArray = Object.keys(source[0]);
let datatable = source.map(d => Array.from(Object.values(d)))
let combined = [ansArray,...datatable];
console.log(combined);
Array.from(Object.keys(d)) and Array.from(Object.values(d)) will return the wrong data if the order of property is wrong.
const source = [{
day: 1,
deliveries: 16,
hours: 9
}, {
day: 2,
deliveries: 19,
hours: 11
}]
const datatable = source.reduce((acc, item, index) => {
if (index == 0) {
acc.push(Object.keys(item));
}
const newRow = acc[0].reduce((rowAcc, prop) => {
rowAcc.push(item[prop]);
return rowAcc;
}, []);
acc.push(newRow);
return acc;
}, [])
console.log(datatable);
Why doesn't the value of variable show? I think it should be 1 or 0 depending on value inside of variable bayar, but why its doesn't work
I've tried to do anything that I can do but it doesn't work like it try to change several code but it doesn't work.
Here's my controller code:
public function generated(){
$data=DB::table("tb_trx_perhitungan_bunga_simpanan")
->selectRaw('trx_bulan')
->get();
return view('crud.form.cobaNampilin',compact('data'));
}
And here's my JavaScript and jQuery code:
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var a;
var array = {!! json_encode($data) !!};
var i;
var b;
$('#bulan').keyup(function(){
var bayar=parseInt($('#bulan').val());
for(i=0;i<=array.length;i++){
if(bayar==array[i].trx_bulan){
a=1;
}
else{
a=0;
}
}
$('#hasil').val(a);
});
});
</script>
I expected the output is 1 or 0
The content of var array I think should be [trx_bulan 1],[trx_bulan 2],[trx_bulan 3],[trx_bulan 4],[trx_bulan 5],[trx_bulan 6] because content of array is an array object. I read that on the website so that's why I use array[index].trx_bulan] to call the value of each index.
Here's the screenshot of table data:
So if you have a data table like:
Then consider the following code:
$(function() {
var a = 0;
/*
In laravel use:
var data = {{json_encode($data)}};
it will translate to something like:
*/
var data = [{
id: 27,
trx_bulan: 1,
trx_tahun: 2018,
tangal_proses: "2018-12-09 07:23:00",
persentase_bunga: 0.2,
id_user: 3
}, {
id: 28,
trx_bulan: 2,
trx_tahun: 2018,
tangal_proses: "2018-12-09 03:42:39",
persentase_bunga: 0.2,
id_user: 3
}, {
id: 29,
trx_bulan: 3,
trx_tahun: 2018,
tangal_proses: "2018-12-09 03:43:43",
persentase_bunga: 0.2,
id_user: 3
}, {
id: 30,
trx_bulan: 4,
trx_tahun: 2018,
tangal_proses: "2018-12-09 03:44:06",
persentase_bunga: 0.2,
id_user: 3
}, {
id: 31,
trx_bulan: 5,
trx_tahun: 2018,
tangal_proses: "2018-12-09 03:45:40",
persentase_bunga: 0.2,
id_user: 3
}, {
id: 33,
trx_bulan: 6,
trx_tahun: 2018,
tangal_proses: "2018-12-09 06:32:38",
persentase_bunga: 0.2,
id_user: 3
}];
$('#bulan').keyup(function(e) {
var bayar = parseInt($('#bulan').val());
a = 0;
$.each(data, function(k, v) {
if (bayar == v.trx_bulan) {
console.log("Hit", v);
a = 1;
}
});
$('#hasil').val(a);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="bulan" />
<br />
<input type="text" id="hasil" />
You may want to consider switching to type="number" or checking that the entry is a number value when the user types something.
Hope that helps.
It never return output because wrong loop condition, the loop for(i=0;i<=array.length;i++) will throw error and $('#hasil').val(a); will not executed.
TypeError: array[i] is undefined
It is because i index is out of range, use the < only
for(i=0; i<array.length; i++)
then if element with ID hasil is not <input> use .html()
$('#hasil').html(a);
And there are several ways to convert to JSON
#json Blade directive
var array = #json($data);
single Curly brackets
var array = {!! json_encode($data) !!};
using toJson()
var array = {!! $data->toJson() !!};
and native php
var array = <?php echo json_encode($array); ?>;
Can you help me to solve this problem?
export class SomePage {
reg = [{apple: 201, ball: 21, cat: 12}, {apple: 202, ball: 65, cat: 15}];
constructor() {
firebase.database().ref('app/test').set({
// i want to set all ***cat*** values here like:
// key1: 12
// key2: 15
})
.
Tried to extract cat values with this method:
let keys = this.reg.map(a => a.cat);
console.log(keys); // <unavailable>
You have your reg array of objects.
Initialize the resultObject
Create a counter to increment the key of resultObject
Filter all cat values from reg array and set it to resultObject.
Update it in your firebase db.
//1
var reg = [{apple: 201, ball: 21, cat: 12}, {apple: 202, ball: 65, cat: 15}];
//2
var resultObject = {};
//3
var count = 0;
//4
reg.filter(function(elem){ resultObject['key'+ ++count] = elem.cat});
//5
constructor() {
firebase.database().ref('app/test').set(resultObject);
}
Figured out a solution:
this.reg.map(a => {
let first = a.ball; // or add any key
let addORupdate = {};
addORupdate[first] = a.cat; // expected value from array
firebase.database().ref('app/test').update(addORupdate);
// this will add 21:12 and 65:15 under the parent "test"
});
I'm making a request for x and y values from a flax/python backend using Polymer and I can read the values in console for the XMLHttpResquest response, but now I need to convert the output into a set of discrete x and y values (so it can be read by C3.js - a framework sitting on top D3 for graphing).
Here's the code I'm using to get the XMLHttpResquest response:
<paper-button affirmative hover on-tap="{{addNewGraph}}">Submit</paper-button>
Polymer("add-graphItem",{
addNewGraph: function () {
var HeaderName = this.$.graphOptionsLoad.$.headerValue.selectedItem.label;
var FunctionName = this.$.graphFunctionsLoad.$.functionValue.selectedItem.label;
console.log("The options are " +HeaderName +" and " +FunctionName);
var params = {};
if (this.$.graphOptionsLoad.$.headerValue.selectedItem) {
params['DataHeader'] = this.$.graphOptionsLoad.$.headerValue.selectedItem.label;
}
if (this.$.graphFunctionsLoad.$.functionValue.selectedItem) {
params['FunctionName'] = this.$.graphFunctionsLoad.$.functionValue.selectedItem.label;
}
this.$.sendOptions.params = JSON.stringify(params);
var x = this.$.sendOptions.go();
// this.$.sendOptions.go();
console.log(x)
// var ajax = document.querySelector("sendOptions");
var results = [];
this.addEventListener("core-response",
function(e) {
console.log(x.response);
}
);
}
});
And here's an example of the output from console.log(x.response);:
{
"graph": [
{
"Header": "MakeModeChange"
},
{
"x": [
0.0,
131.35,
26971.3,
27044.75,
27351.4,
27404.483333333334,
27419.416666666668,
33128.96666666667,
33549.13333333333,
34049.48333333333,
77464.26666666666,
77609.71666666666,
174171.85,
259166.98333333334
]
},
{
"y": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14
]
}
]
}
Ultimately I need the output to look something like:
['x', 0.0, 131.35, 26971.3, 27044.75, 27351.4, 27404.483333333334...],
['y', 1, 2, 3, 4, 5, 6]
Here's a quick and dirty way to do it - not recommended for large scale or if you don't fully trust the response values. Also, obvious, but if their api/data structures changes you're SOL.
xArr = JSON.parse(x.response).graph[1].x
xArr.unshift('x')
yArr = JSON.parse(y.response).graph[2].y
yArr.unshift('y')
You'll get both arrays you'll need, you can combine as needed
How to convert the query string parameters to a JSON object
Code I was written
var actualappt = {
RoomId: 1, HotelId: 29, BookingStartDate: Sept 26 2014, BookingEndDate: Sept 26 2014 , BookingStatusId: '1', BookingTypeId: '1', DepositAmount: 3000, NoOfRooms: 2, UnitPrice: 4000,
Customers: { GuestName: rk, MobileNo: 5656566555, Email: rk#gmail.com, Address: hyd }, Payment_Mode_Id: 4
};
var stringsata = JSON.stringify(actualappt);
var queryString = $.param(actualappt);
Now I am able to convert JSON object to query string and sending to next page, in my page I want reverse process i.e from query string to JSON object
var actualappt = {
RoomId: 1, HotelId: 29, BookingStartDate: "Sept 26 2014", BookingEndDate:"Sept 26 2014" , BookingStatusId: '1', BookingTypeId: '1', DepositAmount: 3000, NoOfRooms: 2, UnitPrice: 4000,
Customers: { GuestName: "rk", MobileNo: 5656566555, Email: "rk#gmail.com", Address: "hyd"}, Payment_Mode_Id: 4
};
var stringsata = JSON.stringify(actualappt);
var queryString = $.param(actualappt);
var recoveredParams = {};
var queryString = decodeURIComponent(queryString)
$.each(queryString.split('&'), function(key, value){
var item= value.split('=');
recoveredParams[item[0]] = item[1];
});
console.log(recoveredParams)