I am trying to capitalize the first letter of each word in the other function.
This is the function to turn each words first letter to capital that I am using.
function capital_letter(str)
{
str = str.split(" ");
for (var i = 0, x = str.length; i < x; i++) {
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}
return str.join(" ");
}
Here’s the second function that I’m trying to use the first one in, but it is not working.
$(document).ready(function() {
$('#list').dataTable({
"ajax":{
url :"list.php",
type: "GET",
error: function(){
$("#post_list_processing").css("display","none");
}
},
"columns": [
{ "data": function capital_letter(item) {
return item.title;
}
},
{ "data": "description" },
{ "data": "time" }
]
});
});
You should only call the function like the following:
$(document).ready(function() {
$('#list').dataTable({
ajax: {
url: 'list.php',
type: 'GET',
error: function() {
$('#post_list_processing').css('display', 'none');
},
},
columns: [{
data: capital_letter(item.title);
},
{ data: 'description' },
{ data: 'time' },
],
});
});
You're redefining the function instead of actually using it... Call it like this;
...
"columns": [
{ "data": capital_letter(item.title) }
...
You are not calling the function correctly. Change the following in your code.
"columns": [
{ "data": capital_letter(item.title) }
Created a working snippet.
function capital_letter(str) {
str = str.split(" ");
for (var i = 0, x = str.length; i < x; i++) {
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}
return str.join(" ");
}
const columns = [{
"data": capital_letter("abc")
},
{
"data": "description"
},
{
"data": "time"
}
]
console.log(columns)
Related
I am using DataTables with ajax and I am trying to dynamically generate a columns list as in the example here: https://datatables.net/examples/ajax/orthogonal-data.html (only in my case I have display and order for all items).
I tried with this approach, but this doesn't work and I am guessing push my sub values wrong.
Input (ajax result):
[{
"itemId": {
"order": "BG007002",
"display": "BG007002"
},
"builtDate": {
"order": "2000-03-01",
"display": "01.03.2000"
},
"openedDate": {
"order": "2005-07-09",
"display": "09.07.2005"
},
"buildingSize": {
"order": 15000,
"display": "15.000"
}
}, // ...
Expected output:
[
{ data: {
_: "itemId.display",
sort: "itemId.order"
}
},
{ data: {
_: "builtDate.display",
sort: "builtDate.order"
}
},
{ data: {
_: "openedDate.display",
sort: "openedDate.order"
}
},
{ data: {
_: "buildingSize.display",
sort: "buildingSize.order"
}
}
]
My approach:
var reportColsShort = $('#reportColsShort').text().slice(0,-1);
var aoCols = [];
var colss = reportColsShort.split(',');
for (var i = 0; i < reportColsShort.split(',').length; i++) {
var aoColss = {};
aoColss['data']['_'] = colss[i].display;
aoColss['data']['sort'] = colss[i].order;
aoCols.push(aoColss); // expected output
}
Error:
Cannot set property '_' of undefined.
Update:
Here is one more reference to what I am trying to achieve:
https://datatables.net/reference/option/columns.render#Examples
You can take the ajax result and then use a map see docs to structure your data like this:
const data = [{
"itemId": {
"order": "BG007002",
"display": "BG007002"
},
"builtDate": {
"order": "2000-03-01",
"display": "01.03.2000"
},
"openedDate": {
"order": "2005-07-09",
"display": "09.07.2005"
},
"buildingSize": {
"order": 15000,
"display": "15.000"
}
}];
const mapResult = data.map((elem) => {
let array = [];
Object.keys(elem).forEach((key) => {
const temp = {
data: {
_: elem[key].display,
sort: elem[key].order
}
}
array.push(temp);
});
return array;
});
console.log(mapResult);
I'm writing a function that takes arguments and add them to form a line to look for data in a JSON file. I've defined a variable for the readFileSync and the add to it the arguments of the function to look for the data.
var jf = require('jsonfile'),
file = 'logins.json',
i = 1;
var jsonData = jf.readFileSync(file);
function getJSONData() {
var n = 1;
var com = '';
do {
if (arguments[n] !== undefined) {
com += `['${arguments[n]}']`;
}
n++;
} while (n < arguments.length);
return com;
}
var h = getJSONData(i, 'operator', 'id');
console.log(jsonData[i] + h);
This is my JSON:
[
{
"operator": {
"id": "avalle",
"pass": "Aa123456",
"something": "idk",
"account": [
{
"type": "asd",
"idk": "asd"
},
{
"type": "asd",
"idk": "asd"
}
]
}
},
{
"operator": {
"id": "oleal",
"pass": "Aa123456",
"something": "idk",
"account": [
{
"type": "asd",
"idk": "asd"
},
{
"type": "asd",
"idk": "asd"
}
]
}
}
]
I should get a line of jsonData[i]['param1']['param2'] that locates the data in the file.
Instead i get undefined or [object Object]['operador']['id']
If you want a property to be returned from the function you can make this change:
function getJSONData(jsonData) {
var n = 1;
var result = jsonData;
do {
if (result[arguments[n]]) {
result = result[arguments[n]]
} else {
console.error(`Property ${arguments[n]} does not exist on obj:`, result)
}
n++;
} while (n < arguments.length);
return result;
}
var h = getJSONData(jsonData[i], 'operator', 'id');
Otherwise you return a string from getJSONData that looks like "[prop1][prop2]" and it will not retrieve a property by trying to concat Object + string
can any one help in this i am trying to compare two different arrays for pushing values when comparision is equal. below are my two(imageslide.therapy),totalValues arrays and i want compare names like cats and dogs. if condition is true then i need to push their images urls.
var imageslide = {
"therapy": [
{
"name": "cats",
"images": [
{ "url": "cat/firstimg.jpg" },
{ "url": "cat/secondimg.jpg" },
{ "url": "cat/thirdimg.jpg" },
{ "url": "cat/fourthimg.jpg" }
]
},
{
"name": "dogs",
"images": [
{ "url": "dog/firstdog.jpeg" },
{ "url": "dog/seconddog.jpg" },
{ "url": "dog/thirddog.jpg" },
{ "url": "dog/fourthdog.jpg" }
]
},
]
}
var totalValues = ["cats","dogs"];
and i tried like below
var imageArray = imageslide.therapy
function compare(imageArray,totalValues ){
imageArray.forEach((e1)=>totalValues.forEach((e2)=>{
if(e1.name==e2){
console.log(e1.name,",",e2)
}
})
For what I understand from your question here is the answer. Please forgive me I don't know much about arrow function so I wrote it in simple javascript.
var imageslide = {
"therapy": [
{
"name": "cats",
"images": [
{ "url": "cat/firstimg.jpg" },
{ "url": "cat/secondimg.jpg" },
{ "url": "cat/thirdimg.jpg" },
{ "url": "cat/fourthimg.jpg" }
]
},
{
"name": "dogs",
"images": [
{ "url": "dog/firstdog.jpeg" },
{ "url": "dog/seconddog.jpg" },
{ "url": "dog/thirddog.jpg" },
{ "url": "dog/fourthdog.jpg" }
]
},
]
}
var totalValues = ["cats","dogs"];
var imageArray = imageslide.therapy
function compare(imageArray,totalValues ){
for(var i=0;i<imageArray.length;i++){
for(var j=0;j<totalValues.length;j++){
if(totalValues[j]=imageArray[i].name){
console.log(imageArray[i].name+"=="+totalValues[j]);
//imageArray[i].images.push({"url": "https://hexasoft.io"});
//break;
return imageArray[i].images;
}
}
}
//printResult(imageArray);
return [];
}
function printResult(resultArray){
for(var i=0;i<resultArray.length;i++) {
console.log(resultArray[i].name);
for(var j=0;j<resultArray[i].images.length;j++){
console.log(resultArray[i].images[j]);
}
}
}
images = compare(imageArray, totalValues);
if(images.length > 0){
for(var i=0;i<images.length; i++){
images[i].push({"url": "your url"});
}
}
Check out the javascript filter function (Link for the docs).
In your case, you want to do something like this:
function getImagesByAnimalName(animal_name){
var imageArray = imageslide.therapy;
var animalImages = imageArray.filter(animalData => {
return animalData.name === animal_name;
})
return animalImages[0].images;
}
Try it like this. The function will return URLs for each element in totalValues array.
var totalValues = ["cats"];
var slides = imageslide.therapy;
function comp(slides, totalValues ){
let retVal;
for( val of totalValues ) {
for( thisTh of slides ) {
if( thisTh.name == val ){
retVal = thisTh.images;
}
}
}
return retVal;
}
The following will create pics, a flat array of image URLs, if this is what you want:
var pics=[].concat(...imageslide.therapy.map(el=>{
if (totalValues.indexOf(el.name)>-1)
return el.images.map(e=>e.url)}))
console.log(pics);
function compare(imageArray, totalValues) {
for (var a = 0; a < imageArray.length; a++) {
for (var j = 0; j < totalValues.length; j++) {
if (totalValues[j] == imageArray[a].name) {
allValues.push(imageArray[a].images);
for (var i = 0; i < allValues.length; i++) {
for(var j = 0; j < allValues[i].length; j++){
buildSlide(allValues[i][j].url);
}
}
}
}
}
displaySlides(slide_index);
}
I am trying to add element "delete:true" after each occurrence of "_rev " mentioned in the below sample request.
Original Request:
{
"docs": [
{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
}
Expected Request:
{
"docs": [
{
"_id": "123",
"_rev": "1-7836",
"_deleted" :true
},
{
"_id": "456",
"_rev": "1-1192",
"_deleted" :true
}
]
}
When I tried the below code,the ""_deleted" :true" is getting inserted after the -rev element is closed. PFB for the same and suggest.
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
for (var value in params.docs[i]) {
if(value == '_rev' && params.docs[i]._rev ){
var string1 = JSON.stringify(params.docs[i]);
var str = ',';
var string2 = '"';
var string3 =str+string2+ '_deleted'+ string2+ ':' + "true" ;
var res = string1 + string3 ;
}
}
}
}
######################
[
"2018-01-23T09:44:23.568738362Z stdout:
{\"_id\":\"123\",
\"_rev\":\"1-7836\"},
\"_deleted\":true"]
Use map and Object.assign instead of generating a string
var output = params.docs.map( s => Object.assign( {}, {"_deleted" :true}, s ) );
You can then convert this to string using JSON.stringify( output );
Demo
var params = {
"docs": [{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
};
var output = params.docs.map(s => Object.assign({}, {
"_deleted": true
}, s));
console.log(output);
var data = {
"docs": [
{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
}
var newData = data['docs'].map(item => {
item._delete = true
return item
})
console.log(newData);
Why don't you simply put ._deleted attribute to doc, like this ?
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
params.docs[i]._deleted = true;
var res = JSON.stringify(params.docs[i]);
}
}
}
Or like this :
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
params.docs[i]["_deleted"] = true;
var res = JSON.stringify(params.docs[i]);
}
}
}
You can reference the not existing attribute directly and assign an value:
#!/usr/bin/js
var myJSON = { "docs": [ { "_id":"123", "_rev":"1-200" } ] }
console.log(myJSON);
myJSON.docs[0]["_deleted"]=true;
console.log(myJSON);
Output of example:
# js append.js
{ docs: [ { _id: '123', _rev: '1-200' } ] }
{ docs: [ { _id: '123', _rev: '1-200', _deleted: true } ] }
Read the more extensive example here: Add new attribute (element) to JSON object using JavaScript
So this might be a duplicate ...
I am getting jsonString object in my ajax call.can any one tell me how to print this object as a dropdown .
[
{
"id" : 3272,
"name" : "a"
},
{
"id" : 3255,
"name" : "b"
},
{
"id"
: 3257,
"name" : "c"
},
{
"id" : 3253,
"name" : "d"
},
{
"id" : 3256,
"name" : "e"
}
]
That's my code:
<script>
$(document).ready(function() {
$("#customerDetails").change(function() {
var value = $('#customerDetails :selected').text();
$.ajax({
type: 'GET',
url: 'environments',
data: {
selectedcustomername: value
},
success: function(result) { //this result is my jsonstring object alert("success");
}
});
});
});
</script>
Let say myJson is
{
"myJson": [
{
"id": 3272,
"name": "a"
},
{
"id": 3255,
"name": "b"
},
{
"id": 3257,
"name": "c"
},
{
"id": 3253,
"name": "d"
},
{
"id": 3256,
"name": "e"
}
]
}
var options = eval(myJson);
Using jQuery to fill options
var length = options.length;
for(var j = 0; j < length; j++)
{
var newOption = $('<option/>');
newOption.attr('text', options[j].name);
newOption.attr('value', options[j].id);
$('#mySelect').append(newOption);
}
Also have a look here
var row=[{"id":3272,"name":"a"},{"id":3255,"name":"b"},{"id"
:3257,"name":"c"},{"id":3253,"name":"d"
},{"id":3256,"name":"e"}];
var select="<select id='x'>";
for(var i=0,l=row.length;i<l;i++){
var item=row[i];
select+="<option value='"+item.id+"'>"+item.name+"</option>";
}
select+="</select>";
document.write(select);
By using simple for loop you can read each value and make a select box
var v = { "myJson": [ { "id": 3272, "name": "a" }, { "id": 3255, "name": "b" }, { "id": 3257, "name": "c" }, { "id": 3253, "name": "d" }, { "id": 3256, "name": "e" } ] }
// in your ajax success block write this and v is your response return by ajax
var str ='<select>';
for(var i=0;i<v.myJson.length;i++){
str += '<option value="'+v.myJson[i].id+'">'+v.myJson[i].name+'</option>';
}
str +='</select>';
$("body").html(str)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body></body>
Here's a working fiddle: https://jsfiddle.net/q1ekcf6z/
var returnData = [{"id":3272,"name":"a"},{"id":3255,"name":"b"},{"id"
:3257,"name":"c"},{"id":3253,"name":"d"
},{"id":3256,"name":"e"}];
var options = '';
returnData.forEach(function(data){
options+= getOption(data.name);
});
var fullDropdown = '<select>' + options + '</select>';
document.write(fullDropdown);
function getOption(textTo){
return '<option>' + textTo + '</option>';
}