Is it possible to populate jstree using a loop? - javascript

Hi I'd like to know if its possible to populate my jstree using a loop instead of hard-coding each node. Below is my code:
api.call("Get", {
typeName: "Device"
}, function (result) {
$('#jstree').jstree({
'plugins': ["checkbox", "sort"],
'core': {
'data':
[
{ id: result[0].id, text: result[0].name },
{ id: result[1].id, text: result[1].name }
]
}
});
});
I make an api call then populate my tree with the returned results. How can I format my JSON using a loop?
This is the main part I need to change:
[
{ id: result[0].id, text: result[0].name },
{ id: result[1].id, text: result[1].name }
]
This is what I've tried:
[
function () {
for(var i = 0; i < result.length; i++){
{ id: result[i].id, text: result[i].name }
}
}
]
Thank you.

Sure.
api.call("Get", {
typeName: "Device"
}, function (result) {
$('#jstree').jstree({
'plugins': ["checkbox", "sort"],
'core': {
'data': (function () {
var results = [];
for(var i = 0; i < result.length; i++){
results.push({ id: result[i].id, text: result[i].name });
}
return results;
})()
}
});
});

Related

Comparison of two arrays regarding the text

I've got two arrays which i want to compare. Therfore i want to check if they got equal elements regarding the "text": .... If its equal it should return true, otherwise return false
englishData = [
{"data":"sandwich","text":"Sandwich"},
{"data":"toast","text":"Cuisine"},
{"data":"fries","text":"Pommes"},
{"data":"salad","text":"Salad"},
]
franceData = [
{"data":"sandwich","text":"Sandwich"},
{"data":"toast","text":"Kitchen"},
{"data":"fries","text":"Pommes"}]
So far i tried it with a normal for-loop, like :
for (let i = 0; i < actualData; i++) {
for (let j = 0; j < plannedData; j++) {
if (actualData[i].text === plannedData[i].text) {
return true
} if (actualData[i].text != plannedData[j].text) {
continue;
}
}
return false
}
}
Because of the different length, i wanted to compare each element in franceData with all elements in the original array englishData.
Its kinda woking, but im not sure if it's really the best solution regarding the performance, ... .
I also thought about some if statements, like:
if(franceData.text.includes(englishData.text)){ return true }
If you are looking to find out common elements, you can try something like this
englishData = [
{ data: "sandwich", text: "Sandwich" },
{ data: "toast", text: "Cuisine" },
{ data: "fries", text: "Pommes" },
{ data: "salad", text: "Salad" },
];
franceData = [
{ data: "sandwich", text: "Sandwich" },
{ data: "toast", text: "Kitchen" },
{ data: "fries", text: "Pommes" },
];
var res = englishData.filter((ede) =>
franceData.some((fde) => ede.text === fde.text)
);
console.log(res);
output:
[
{ data: 'sandwich', text: 'Sandwich' },
{ data: 'fries', text: 'Pommes' }
]
You can use map() in the place of filter to get just true or false for every match.
englishData = [
{ data: "sandwich", text: "Sandwich" },
{ data: "toast", text: "Cuisine" },
{ data: "fries", text: "Pommes" },
{ data: "salad", text: "Salad" },
];
franceData = [
{ data: "sandwich", text: "Sandwich" },
{ data: "toast", text: "Kitchen" },
{ data: "fries", text: "Pommes" },
];
var res = englishData.map((ede) =>
franceData.some((fde) => ede.text === fde.text)
);
console.log(res.join("\n"));
output:
true
false
true
false

Datatables date sort vs date display

I am using Datatables to display a table and I am pulling a list of datestimes from a MySQL database. These date times are not standard dates and look like this:
12/30/19 # 04:17 pm
How can I sort these accurately with Datatables?
Here is my code:
getRes(function (result) { // APPLIED CALLBACK
$('#resdatatable').DataTable({
data: result, // YOUR RESULT
order: [[ 0, "desc" ]],
autoWidth: false,
responsive: true,
columns: [
{ data: 'id', title: 'ID' },
{ data: 'bookingdatetime', title: 'Booking Date' },
{ data: 'name', title: 'Name' },
{ data: 'class', title: 'Class' },
{ data: 'pickupdatetime', title: 'Pick up' },
{ data: 'duration', title: 'Duration' },
{ data: 'dropdatetime', title: 'Drop off' },
{ data: 'age', title: 'Age' },
{ data: 'coverage', title: 'Coverage' },
{ data: 'quote', title: 'Quote' },
{
data: 'status',
title: 'Status',
render: function(data, type, row) {
let isKnown = statusList.filter(function(k) { return k.id === data; }).length > 0;
if (isKnown) {
return $('<select id="resstatus'+row.id+'" onchange="changeResStatus('+row.id+')" data-previousvalue="'+row.status+'">', {
id: 'resstatus-' + row.id, // custom id
value: data
}).append(statusList.map(function(knownStatus) {
let $option = $('<option>', {
text: knownStatus.text,
value: knownStatus.id
});
if (row.status === knownStatus.id) {
$option.attr('selected', 'selected');
}
return $option;
})).on('change', function() {
changeresstatus(row.id); // Call change with row ID
}).prop('outerHTML');
} else {
return data;
}
}
}
]
});
});
/**
* jQuery plugin to convert text in a cell to a dropdown
*/
(function($) {
$.fn.createDropDown = function(items) {
let oldTxt = this.text();
let isKnown = items.filter(function(k) { return k.id === oldTxt; }).length > 0;
if (isKnown) {
this.empty().append($('<select>').append(items.map(function(item) {
let $option = $('<option>', {
text: item.text,
value: item.id
});
if (item.id === oldTxt) {
$option.attr('selected', 'selected');
}
return $option;
})));
}
return this;
};
})(jQuery);
// If you remove the renderer above and change this to true,
// you can call this, but it will run once...
if (false) {
$('#resdatatable > tbody tr').each(function(i, tr) {
$(tr).find('td').last().createDropDown(statusList);
});
}
function getStatusList() {
return [{
id: 'Confirmed',
text: 'Confirmed'
}, {
id: 'Unconfirmed',
text: 'Unconfirmed'
}, {
id: 'Communicating',
text: 'Communicating'
}, {
id: 'Open',
text: 'Open'
}, {
id: 'Closed',
text: 'Closed'
}, {
id: 'Canceled',
text: 'Canceled'
}, {
id: 'Reallocated',
text: 'Reallocated'
}, {
id: 'No Show',
text: 'No Show'
}];
}
I need to sort bookingdatetime, pickupdatetime, dropdatetime accurately (they are currently being converted into MM/DD/YY in the PHP script)
Maybe you can prepend hidden <span> elements containing the respective unix timestamps in the cells that have dates (by manually parsing the dates). Then using such columns to sort alphabetically would practically sort time-wise.

JSON Formatting with javascript

Hello all I have a question.
With this code:
targetingIdeaService.get({selector: selector}, function (error, result) {
var string = JSON.stringify(result)
console.log(string)
})
I get this result:
"totalNumEntries":700,
"entries":[
{
"data":[
{
"key":"KEYWORD_TEXT",
"value":{
"attributes":{
"xsi:type":"StringAttribute"
},
"Attribute.Type":"StringAttribute",
"value":"nike ddd8ea95"
}
},
{
"key":"COMPETITION",
"value":{
"attributes":{
"xsi:type":"DoubleAttribute"
},
"Attribute.Type":" DoubleAttribute",
"value":"0.8726547440705715"
}
},
{
"key":"AVERAGE_CPC",
"value":{
"attributes":{
"xsi:type":"MoneyAttribute"
},
"Attribute.Type":"MoneyAttribute",
"value":{
"ComparableValue.Type":"Money",
"microAmount":"16769286"
}
}
},
{
"key":"SEARCH_VOLUME",
"value":{
"attributes":{
"x si:type":"LongAttribute"
},
"Attribute.Type":"LongAttribute",
"value":"5609289"
}
}
]
}
]
}
And with this one i get the following:
targetingIdeaService.get({selector: selector}, function (error, result) {
var resultaten = result;
var res = resultaten.entries;
for(var i = 0; i < res.length; i++){
console.log(resultaten.entries[i])
}
})
Output
{ data:
[ { key: 'KEYWORD_TEXT', value: [Object] },
{ key: 'COMPETITION', value: [Object] },
{ key: 'AVERAGE_CPC', value: [Object] },
{ key: 'SEARCH_VOLUME', value: [Object] } ] }
Now im looking to format the JSON a certain way, It has to look like this example.
Notice: the key value pairs of json data.
[
{
"KEYWORD_TEXT": "red herring 9e23f4ad",
"SEARCH_VOLUME": 4574730
},
{
"KEYWORD_TEXT": "nike 656e95f0",
"SEARCH_VOLUME": 3442386
},
etc...
]
Basically the Key and the value of that key next to eachother. How to do this?
You can map the keys to values like following -
resultaten = result.data.map(function (item) {
return {
[item.key]: item.value
}
});
JSON.stringify(resultaten);

jQuery dataTable not showing data by default

I have a jquery DataTable as
html page
<div id="content">
</div>
js code
(function ($) {
'use strict';
var module = {
addTable: function () {
var output = '<table id="table1"></table>';
$('#content').append('<p></p>' + output);
var data = [];
data = this.getData();
$('#table1').dataTable({
"data": data,
"columns": [
{
"title": 'Name',
mDataProp: 'name',
width: '20%'
},
{
"title": 'Company',
mDataProp: 'company'
},
{
"title": 'Salary',
mDataProp: 'salary'
}],
'scrollY': '400px',
'scrollCollapse': false,
'paging': false
});
},
getData: function () {
var arr = [];
for (var i = 0; i < 100; i++) {
var obj = {
name: 'John',
company: 'XYZ',
salary: '$XYZ'
};
arr.push(obj);
}
return arr;
}
};
$(document).ready(function () {
$('#content').append('Loading....');
module.addTable();
});
})(jQuery);
On initial load, it shows an empty table. Data comes after performing some search. How to show the data by default on initial load?
This is due to javascripts asynchronicity. getData() is not finished at the time of the dataTable initialization. You could make some refactoring, so getData invokes addTable as a callback instead.
var module = {
addTable: function (data) {
var output = '<table id="table1"></table>';
$('#content').append('<p></p>' + output);
$('#table1').dataTable({
"data": data,
"columns": [
{
"title": 'Name',
mDataProp: 'name',
width: '20%'
},
{
"title": 'Company',
mDataProp: 'company'
},
{
"title": 'Salary',
mDataProp: 'salary'
}],
'scrollY': '400px',
'scrollCollapse': false,
'paging': false
});
},
getData: function (callback) {
var arr = [];
for (var i = 0; i < 100; i++) {
var obj = {
name: 'John',
company: 'XYZ',
salary: '$XYZ'
};
arr.push(obj);
}
return callback(arr);
},
init : function() {
this.getData(this.addTable);
}
};
...
module.init();
init() calls getData(callback) with addTable as param, addTable have had the param data added.
demo -> http://jsfiddle.net/bLzaepok/
I assume your getData code is only per example, and you are using AJAX (or whatever) IRL. Call the callback in the callback :
getData: function (callback) {
$.ajax({
...
success : function(data) {
callback(data);
}
});
}

commit changes on existing records in extjs store

my issue is that I want to update existing store and show the changes on the grid.
What I'm doing to update is :
var record = store.getById(me.internalParameters.editInfo.id);
//console.log(me.InfoEditorPanel.hardwareIdField.value);
record.set('hardwareid', me.InfoEditorPanel.hardwareIdField.value);
record.set('location', me.InfoEditorPanel.locationField.value);
record.set('isActive', me.InfoEditorPanel.isActiveField.value);
record.commit();
store.load();
Here what I use to build the grid.
Utils.getPanelListGrid = function (parameters) {
if (parameters.initParameters == null)
parameters.initParameters = {};
var initParameters = parameters.initParameters;
initParameters.gridColumns = [
{ header: "ID", dataIndex: "id", flex: 1 },
{ header: "Hardware ID", dataIndex: "hardwareid", flex: 1 },
{ header: "Location", dataIndex: "location", flex: 1 },
{ header: "Active", dataIndex: "isActive", flex: 1 }
];
return new Backend.shared.MyDataGrid(parameters);
};
Ext.define(
"shared.MyDataGrid", {
extend: "Ext.grid.Panel",
xtype: "MyDataGrid",
title: "MyDataGrid - Hardcoded values",
initParameters: {
storeIdProperty: null,
},
initComponent: function () {
this.store = Ext.create('Ext.data.Store', {
storeId: 'myStore',
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'items'
}
},
fields: ['id', 'hardwareid', 'location', 'isActive'],
data: {
'items': [{
'id': '123456',
'hardwareid': "HID-159",
'location': "Bedroom",
'isActive': "No"
}, {
'id': '789456',
'hardwareid': "HID-357",
'location': "Kitchen",
'isActive': "Yes"
}, {
'id': '147852',
'hardwareid': "HID-149",
'location': "Guest-room",
'isActive': "Yes"
}
]
}
});
this.columns = this.initParameters.gridColumns;
this.listeners = {
selectionchange: {
scope: this,
fn: function (selectionModel, selectedRecords, eventOptions) {
this.selectedIds = [];
this.selectedItems = [];
if (selectedRecords != null) {
for (var i = 0; i < selectedRecords.length; i++) {
var item = selectedRecords[i].data;
this.selectedIds.push(item[this.initParameters.storeIdProperty]);
this.selectedItems.push(item)
}
}
if (this.initParameters.selectionChangeCallback != null)
this.initParameters.selectionChangeCallback(this.selectedIds, this.selectedItems);
}
}
};
shared.MyDataGrid.superclass.initComponent.call(this);
},
getRecordCount: function () {
return this.getStore().getTotalCount();
},
getSelectedIds: function () {
return this.selectedIds;
},
getSelectedItems: function () {
return this.selectedItems;
}
});
Can anyone please explain what should I do exactly to make the grid show the updated row?
I suggest that use the following code in your 'selectionchange' event.
this.getStore().load({
params:{
'yourModelIdProperty':'selectedId'
}
});
It's call an store proxy. You should write a function for that proxy and load the updated data.

Categories