JQuery Datatables Row Data From AJAX Source - javascript

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();

Related

What is the correct way to handle this data using jQuery?

I have a list of html elements with data attributes, which I would like to assemble into a jQuery object and manipulate the values.
What is the best way to dynamically add these in an each loop so that I can easily access the data as so: data.name and data.name.prop?
I want all the naming conventions to be dynamic and based on the data.
I based my code on the top answer from here: How to create dynamically named JavaScript object properties?
So far I have:
$('.licences-list .data div').each(function(index) {
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
cats.push(data)
})
But when I try to iterate over the data array, like so:
$.each(cats, function(key, value){
$('<div class="card"><p>'+value+'</p></div>').appendTo('#commercial-licenses');
});
I just get [object Object] output... and I'm not sure why!
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
Each time you loop through, you're actually just adding an empty object (data) to your array (cats). You're then assigning a named property to that array (cats) which $.each has no idea about (it ignores them because it's iterating over an actual array).
My guess is you want an object map which is something like: var cats = { "f1": "feline 1", "f2": "feline " };
In that case what you want is:
var cats = {};
$('.licences-list .data div').each(function(index) {
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
})
If you want an array that contain more values than just strings (or whatever data you have added to the element), you create new objects each time and append them to the cats array:
var cats = [];
$('.licences-list .data div').each(function(index) {
cats.push({
'id': $(this).find('p').data('cat'),
'name': $(this).find('p').data('catname')
});
})
This will then give you an array that you can use $.each over, and access the values using: value.id, value.name
Don't over complicate it.
$('.div').attr('data-attribute', 'data-value');
using your example:
$('.licences-list .data div').attr('attribute-name', 'attribute-value');

Can I get the list of Caman.js filters?

Is there any way to return the list of all the built-in filters within the library.
For example:
var caman_Default_List = [];
Caman('myCanvas', function(){
caman_Default_List= this.getAllFilters();
});
For now I'm using this and it works okay:
var filters =
[
"vintage", "lomo", "clarity", "sinCity", "sunrise",
"crossProcess", "orangePeel", "love", "grungy", "jarques", "pinhole",
"oldBoot", "glowingSun", "hazyDays", "herMajesty", "nostalgia",
"hemingway", "concentrate"
];
myList.push(filters[ some filters ]);
Caman("#myCanvas", function(){
this[myList[index]]().render();
});
But I was wondering if there is a way to get the values of the filters without delcaring them customly. (eg. list = [ "vintage", "lomo", ......... ])
I was looking through their docs, but could not find anything helpful for the data you are trying to get. I took a look at their code and came up with the below for you.
I am not sure I would 100% trust the code, because the order of properties might change, but at least it gives you what you wanted.
console.log(Object.keys(Caman.prototype).slice(75, 93))
<script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js"></script>
I used the code below to achieve what I wanted as #AndrewLohr stated:
//Declare lists to store filter names
var list4,list5,list6,list7 = [];
//Get Caman Filters (Samples : "vintage", "clarity", ... )
list4 = (Object.keys(Caman.prototype).slice(75, 93));
list5 = list4.toString().toUpperCase(); //To upper Case as string value (use as Label Button Name)
//Get Caman Filters (Customs : "brightness", "saturation")
list6 = Object.keys(Caman.prototype).slice(45, 55);
//Add some more elements in the list
list6.push("clip", "stuckBlur", "exposure", "noise", "sharpen");
list7 = list6.toString().toUpperCase(); //To upper Case as string value (use as Slider Name)
//Print lists
console.log(list4);console.log(list5);console.log(list6);console.log(list7);
<script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js"></script>

How to push new key/value pair into external json file? [duplicate]

I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
I want to add a new item to the array, such as
{"teamId":"4","status":"pending"}
to end up with
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.
elementToPush = [1, 2, 3]
if (!obj.arr) this.$set(obj, "arr", [])
obj.arr.push(elementToPush)
(This answer may not be relevant to this particular question, but may help
someone else)
Use spread operator
array1 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Organization"
}
];
array2 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Division"
}
];
array3 = [
{
"column": "Level",
"operator": "=",
"value": "Country"
}
];
console.log(array1.push(...array2,...array3));
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<i class="fa fa-shopping-cart"></i>Add to cart'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
How do I store a simple cart using localStorage?

make json from table

I want to make specific json from table. I have a table, which has rows and 4 columns.
Here is my table I want to build an jsonarray from the table.
First value in the left column is key of json and last value in the right column is a valueof json.
I mean I want to get from table jsonarray, it must look as
json_from_form = [{color: 'id',
name: "mouse",
x: "table",
y: "book"}];
I have tried to build json, but have a problem with structure and setting a key in json object.
Please help me to buld right structure of json object.
var json_from_form_tmp = {};
$('#table').find('tbody tr').each(function (i) {
//var name = $(this).find('td:first').text();
json_from_form_tmp[i] = {
imd: $(this).find('td:eq(3) input').val()
};
});
console.log(json_from_form_tmp);
Here is my DEMO
You should use the jQuery map-function for this, here is an example:
$(function () {
var m = $("table tr").map(function (index, e) {
return {
color: $(e).children().eq(0).text(),
name: $(e).children().eq(1).text()
}
}).get();
});
Where m will be an array of objects as defined inside the map function.
To set a property of the object (json_from_form_tmp), use the ['propertyName'] notation.
//get the name of the property from the first column
var name = $(this).find('td:first').text();
//use that name as the name of the property. Your value fetch was right!
json_from_form_tmp[name] = $(this).find('td:eq(3) input').val();
Here is your fiddle with a tiny modification.
http://jsfiddle.net/bMzq8/32/

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