October 22, 2024
Chicago 12, Melborne City, USA
javascript

How to Execute a Javascript Callback based on a Variable or Parameter


I have an array that is passed to React from a Laravel back end, representing columns in a database. I iterate over this array to construct headings for a table.

For each column, I want to run a callback function to mutate or transform the corresponding data (of each row) for each column.

For example, a Boolean would be transformed, so "Yes", or "No" for 1 or 0 (a TinyInt). Here is what I have so far.

const callbacks = {
    name: function(name) {
        console.log(name);
    },
    completed: function(name) {
        console.log(name);
    },
    created_at: function(name) {
        console.log(name);
    },
    updated_at: function(name) {
        console.log(name);
    },
};

The React component that builds each row of the table is below.

export default function Row({ can, buttons, row }) {
    
    

    return (
        <>
            {
                Object.keys(row).map((k, i) => {
                    if(k !== "id") { 
                        return ( <td key={ i } className="whitespace-nowrap p-4">{ row[k] }</td> )
                    }
                })
            }
            { buttons(can, row.id) }
        </>
    );
}

Where the { row[k] } is outputted, is where I need to transform the data, based on the available callback functions and the column name, found in the variable k.

Can anyone help me figure this out? There’s likely an easy way to do this dynamically but I don’t know enough Javascript to figure it out.

I tried using an array to "map" the column names to the callback function, but I couldn’t get that to work.

I also may need to associate a column name to a different callback function, such as a callback function named active for numerous column names, ie completed, banned, has_uploaded, etc – anything that could also be Boolean.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video