Selectize.js - not showing options - javascript

I have an array that I send from the backend, from which I create a new array of objects, for which I then use JSON.stringify to make it ready for the selectize, the array looks like this then:
[{"question":"Challenge question"},{"question":"Challenge question"},{"question":"Challenge question"}... and so on
I am trying to use that new array with selectize, but no option gets rendered:
This is the script:
var engagementsOptions = [];
icoop.engagements.map(function(item) {
engagementsOptions.push({
"question" : item
});
});
$('#engagement_question').selectize({
options: JSON.stringify(engagementsOptions),
create: true,
});

I think there is a problem with the string you are constructing for the options argument. I think it should be a comma-delimited string. Try something like this maybe (not tested with selectize, just based on the docs)?
//example data
var data_from_server = [{"question":"Challenge question 1"},{"question":"Challenge question 2"},{"question":"Challenge question 3"}];
var engagementsOptions = [];
data_from_server.map(function(item) { engagementsOptions.push(item["question"]); });
$('#engagement_question').selectize({
options: engagementsOptions.join(','),
create: true,
});

Related

Javascript Papaparse Select specific columns using Lodash _.pick() results in empty data

As stated in previous questions here and on Google, I've added a step function to alter the data and provide me with the specific columns I need.
Here was a comment that said to use Lodash _.pick() method: https://stackoverflow.com/a/59944480/4236332
However, when doing that I end up with a completely empty results output.
Code:
parseFile(){
Papa.parse( this.file, {
header: true,
skipEmptyLines: true,
step: (results, parser) => {
results.data = _.pick(results.data , [ 'column1', 'column2']);
return results;
},
complete: function( results ){
console.log(results.data)
this.content = results;
this.parsed = true;
}.bind(this)
});
}
Before vs. After:
First console log holds the colums in the JSON I need plus several I want to filter out, Second log is completely empty.
Tried removing it from the step function and doing it in the complete function but same output.
EDIT 1:
I have tried testing the _.pick function on results.data[0] and this does work, so something is preventing _.pick() of looping through all json records in the list results.data?
Managed to fix this issue by looping through it with a _.map() function. This way it goes through every object in the array with the ._pick() method.
results.data = _.map(results.data, obj => _.pick(obj, [ 'column1','column2']));

Add [DataObject] to exsisting array with var key

Using Cordova, I am trying to get an Object to add to an array. I have this working on node JS using :
theData = {[varkey]:DataObject};
But I can't get this to work the same way within my javascript that cordova runs.
I need to do the following:
var TownName = 'Auckland', var townData = (JSON Data);
theArray = new Array();
theArray[TownName] = townData;
I need to be able to call it back as:
theArray['Auckland']
Which will return (JSON Data)
But it doesn't want to store the data with the key inside the array.
I have also tried:
theArray.TownName = townData;
theArray = [{TownName:townData}];
theArray = {[TownName]:townData}];
Nothing wants to store the data.
Any suggestions?
::EDIT::
data.theData =
"Auckland"[
{
"username":"pndemoname1",
"number":"373456",
"www":"http://373456.pndemoname1",
"icon":"/imgs/pndemoname1.png"
},
{
"username":"pndemoname2",
"number":"373458",
"www":"http://373458.pndemoname2",
"icon":"/imgs/pndemoname2.png"
}
data.town = "Auckland";
townData = new Array();
alert(JSON.stringify(data.theData))//Alerts theData
townData[data.town] = data.theData
alert(townData[townName]) //Alerts undefined
::EDIT2::
Re-defining the array within the function that deals with all of the data, seems to make it work.
As per my answer, the issue was that I assumed javascript vars are global.
Use objects or an array of objects.
A data structure like this:
{
town1: town1Data,
town2: town2Data,
}
Or more common:
[
{
name: "Town 1",
data: {...}
},
{
name: "Town 2",
data: {...}
},
]
For reference:
http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/
I got what you're trying to do, to add property names dynamically to your object is first, by making sure you are using an OBJECT instead of an array, so when you want to store something you will do the following:
var _obj = {}, _something = 'xyz';
_obj[ _something ] = { ... }; // json structure
The problem you're facing is that you want to assign a string value as a key inside your array, which will not work.
However, you can still use the array you defined and do the following:
var _array = new array();
_array.push( { .... } ); // insert json structure
Remember! By using the array you will have to loop through all values every time you want to access your key, just as the best practice to avoid getting into errors.
Good luck.
The issue was that I didn't define the array within the function of where I was trying to add the information to.
I assumed the var was global (Too much PHP)

Turn Observable Array into nested JSON

I'm having a problem getting an array of information stored properly as JSON.
I made a fiddle to illustrate the problem. Enter a set of tags and take a look at the console to see the output.
More explanation:
So I have an input that takes in a comma-separated list of tags, which I then format.
function createTagArray() {
// given an input value of 'tag1, tag2, tag3'
// returns array = ['tag1', 'tag2', 'tag3']
}
I thought what I needed to do next was the following:
loop over the array and create a 'tag' object for each item which also includes an id for the tag and the id of the contact the tag is associated with.
Each object is pushed to tags, an observable array.
function single_tag(id, contactId, tagLabel) {
var self = this;
self.id = id;
self.contactId = contactId;
self.tagLabel = tagLabel;
}
function createTags() {
var array = createTagArray();
for (var i = 0; i < array.length; i++) {
self.tags().push(new single_tag(uuid.generate(), self.contactId, array[i]));
}
}
Then, I converted it into JSON
self.contactInformation = function() {
return ko.toJS({
"id": self.contactId,
"firstname": self.firstname(),
"lastname": self.lastname(),
... other fields ...
"tags": self.tags(),
})
}
But, when I inspect the console output of calling this function, tags is a collection of arrays, not a nice json object.
How do I get it formatted correctly?
I tried this suggestion, and the tag json is structured correctly, but it is stored with escaped quotes, so that seems wrong.
Thanks for all the help!
I would recommend you knockout.mapping plugin for KO, it allow map complicated JSON structure to view model, even without declarations.
From the documentation
Let’s say you have a JavaScript object that looks like this:
var data = {
name: 'Scot',
children: [
{ id : 1, name : 'Alicw' }
]
}
You can map this to a view model without any problems:
var viewModel = ko.mapping.fromJS(data);
Now, let’s say the data is updated to be without any typos:
var data = {
name: 'Scott',
children: [
{ id : 1, name : 'Alice' }
]
}
Two things have happened here: name was changed from Scot to Scott and children[0].name was changed from Alicw to the typo-free Alice. You can update viewModel based on this new data:
ko.mapping.fromJS(data, viewModel);
And name would have changed as expected. However, in the children array, the child (Alicw) would have been completely removed and a new one (Alice) added. This is not completely what you would have expected. Instead, you would have expected that only the name property of the child was updated from Alicw to Alice, not that the entire child was replaced!
...
To solve this, you can specify which key the mapping plugin should use to determine if an object is new or old. You would set it up like this:
var mapping = {
'children': {
key: function(data) {
return ko.utils.unwrapObservable(data.id);
}
}
}
var viewModel = ko.mapping.fromJS(data, mapping);
In the jsfiddle you were using Knockout 3.0 which doesn't have support for textInput. This was added in 3.2. To use version 3.2 you need to use a cdn such as this: http://cdnjs.com/libraries/knockout
There was typeo in your binding. sumbit should be submit.
There was a problem with your constructor for single_tag. id was not used so I removed it:
function single_tag(contactId, tagLabel) {
var self = this;
self.contactId = contactId;
self.tagLabel = tagLabel;
}
Currently also contactId is not set because the observable has not been set to a value.
To convert to JSON you need to use ko.toJSON instead of ko.toJS:
self.contactInformation = function() {
return ko.toJSON({
"firstname": self.firstname(),
"tags": self.tags(),
})
}
Now when the console writes out an array appears:
{
"firstname":"test",
"tags":[
{"tagLabel":"test1"},
{"tagLabel":"test2"},
{"tagLabel":"test3"}
]
}
JsFiddle
So my problem was more basic than I was realizing. I'm using JSON Server to serve up my data, and I was pulling information from two parts of the database (contacts & tags).
When I tried to update my tags, I was trying to apply them to a property that didn't exist on the contact JSON in my database. Posting the tags separately worked though.

JQuery Datatables Row Data From AJAX Source

In the past I've always used this to get a hidden column's data. I would hide the column with a css class, but the responsive feature doesn't work well with these.
var td = $('td', this);
var ID = $(td[0]).text();
So I found an alternative, by hiding the columns with these classes with the responsive feature.
"columnDefs": [
//Responsive classes
{ className: 'never', targets: 0 }, //Hide on all devices
{ className: 'all', targets: 1 }, //Show on all devices
]
and then I use either one of these.
var rowData = oTable1.fnGetData(this);
var rowData = oTable1.api().row(this).data();
//Grab the first indexed item in the list
var ID = rowData[0];
That works well if you don't have an AJAX source. It will return a comma separated list of the row data. However, when I try to use this with an AJAX source I just get [object Object] back (instead of a comma separated list) if I output the rowData variable in an alert.
How do I get the row data out of a table with an AJAX source?
It seem to be stored as string so [1, 2, 3] became [object Object] when you turn it into string. Do yourString = yourList.join(',') and store yourString to keep the coma-separated string.
For an object:
yourString = (function () {
var list = [];
for(var i in yourList)
if(yourList.hasOwnProperty(i))
list.push(yourList[i]);
return list.join(',');
})();
The function is not needed, it's just to limit the variables scope.
I ended up using an answer I found here.
Converting a JS object to an array
I can pull the entire row data from the table with this.
var rowData = oTable1.api().row(this).data();
In the console log I can see that it returns a javascript object like this.
Object { id="123456", full_name="Samuel Smith", Last_name="Smith" }
I use this function to convert the object into an array.
var array = $.map(rowData, function (value, index) {
return [value];
});
In the console log, my array would appear like this.
["123456", "Samuel Smith", "Smith"]
I can then extract any item from the array like this.
alert(array[0]);
Simplifying madvora's example:
var rowData = oTable1.api().row(this).data().to$();
rowDataArray = rowData.toArray();

Issue with using JSON.stringify after using jQuery.map

I am writing a bookmarklet (that will eventually be a plugin) to scrape web pages for list items in jQuery under a specified div. I'm having an issue with using JSON.stringify
The following code allows me to convert each individual item to JSON, but has issues when using join to concatenate each string.
var dMap = $("div").filter($("#<div-id>")).find("li").map(function() {
var iObject = {
id: $(this).data('id'),
text: $(this).text(),
list_name: $(this).closest('div').attr('id')
};
return JSON.stringify(iObject);
});
console.log(dMap);
This second snippet of code creates each object in the array correctly, but the resulting array doesn't log the resulting JSON.
var dMap = $("div").filter($("#,div-id.")).find("li").map(function() {
return {
id: $(this).data('id'),
text: $(this).text(),
list_name: $(this).closest('div').attr('id')
};
});
console.log(dMap);
var json = JSON.stringify(dMap);
console.log(json);
Any ideas?
According to the documentation for .map:
As the return value is a jQuery-wrapped array, it's very common to get() the returned object to work with a basic array.
Have you tried:
var json = JSON.stringify(dMap.get());

Categories

Resources