I am new to JS. I have the following syntax which I need to loop through array.
{
text: newcol[4],
action: function (e, dt, node, config) {
dt.order([[4, "desc"]]).draw();
}
}
Let's say I have an array var nOrder = [4,5]; I want the following syntax to be generated - above syntax is getting repeated twice (as per length of array) and taking values 4 and 5.
buttons = [
{
text: newcol[4],
action: function (e, dt, node, config) {
dt.order([[4, "desc"]]).draw();
}
},
{
text: newcol[5],
action: function (e, dt, node, config) {
dt.order([[5, "desc"]]).draw();
}
}
];
Is this what you need? I don't think you need to use JQuery.
function generateSyntax(array) { // The argument should be an array such as [4, 5]
var resultSyntax = ""; // Every time you loop through the array, add some syntax here.
resultSyntax += "buttons = [\n";
for (var i in array) {
resultSyntax += ` {
text: newcol[` + array[i] + `],
action: function (e, dt, node, config) {
dt.order([[` + array[i] + `, "desc"]]).draw();
}
},\n`; // Add the syntax, with the number in between brackets ("[" and "]")
}
resultSyntax += "];"
return resultSyntax;
}
If you want to get it as an actual array, you can use this (which is slower but safe):
function generateSyntax(array) { // The argument should be an array such as ["4", 5, "2"]
var resultSyntax = ""; // Every time you loop through the array, add some syntax here.
resultSyntax += "buttons = [\n";
for (var i in array) {
resultSyntax += ` {
text: newcol[` + (parseInt(array[i] + "") != parseInt(array[i] + "") ? 0 : parseInt(array[i] + "")) + `],
action: function (e, dt, node, config) {
dt.order([[` + (parseInt(array[i] + "") != parseInt(array[i] + "") ? 0 : parseInt(array[i] + "")) + `, "desc"]]).draw();
}
},\n`; // Add the syntax, with the number in between brackets ("[" and "]")
}
resultSyntax += "];"
return resultSyntax;
}
At the location of where you want to unpack the buttons object, use
// ... assign the newcol array and the dt.order function
var buttons;
eval(generateSyntax(myArrayToParse));
// do stuff with the resultant buttons variable.
This will change all non-number parameters to generateSyntax to 0, to make the eval call safer. As a result, generateSyntax will accept both number and string parameters.