Soy nuevo en JS. Tengo la siguiente sintaxis que necesito para recorrer la matriz.
{ text: newcol[4], action: function (e, dt, node, config) { dt.order([[4, "desc"]]).draw(); } } Digamos que tengo una matriz var nOrder = [4,5]; Quiero que se genere la siguiente sintaxis: la sintaxis anterior se repite dos veces (según la longitud de la matriz) y toma los valores 4 y 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(); } } ];¿Esto es lo que necesitas? No creo que necesites usar 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; }Si desea obtenerlo como una matriz real, puede usar esto (que es más lento pero seguro):
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; }En la ubicación donde desea desempaquetar el objeto de botones, use
// ... assign the newcol array and the dt.order function var buttons; eval(generateSyntax(myArrayToParse)); // do stuff with the resultant buttons variable. Esto cambiará todos los parámetros que no sean números para generateSyntax a 0, para hacer que la llamada a eval sea más segura. Como resultado, generateSyntax aceptará parámetros numéricos y de cadena.