Sending the current object from a forEach loop as an argument to a function

There seems to be an issue with an object structure like the following:

let clients = [{
  "id": 1,
  "first_name": "Felipe",
  "last_name": "Aiken",
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6b0b7bfbdb3b8e696e5e0e6f8b5b8">[email protected]</a>",
  "gender": "Male",
  "ip_address": "13.189.73.39"
}, {
  "id": 2,
  "first_name": "Renell",
  "last_name": "Andreone",
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="493b28272d3b2c26272c780921203a3d283d3a672a2624">[email protected]</a>",
  "gender": "Female",
  "ip_address": "196.153.244.124"
}];

If you try using it in a forEach loop as shown below:

clients.forEach(function(client) {
    console.log(client);
    let tbody = document.querySelector('tbody');
    let newObj = {
        'name': 'client.first_name'
    };
    tbody.innerHTML = tbody.innerHTML + '\
        <tr>\
            <td>' + client.id + '</td>\
            <td>' + client.first_name + '</td>\
            <td>' + client.last_name + '</td>\
            <td>' + client.email + '</td>\
            <td>' + client.gender + '</td>\
            <td><button onclick="setClientInfo(' + (newObj) + ')" class="btn btn-primary">View</td>\
        </tr>\
    ';
});

Upon clicking the "View" button for any item, an "Unexpected error" message shows up in the console referencing this code snippet:

setClientInfo([object Object])

The simple setClientInfo function is defined as follows:

function setClientInfo(client) {
    console.log(client);
}

Any assistance on this matter would be highly appreciated.

Cheers!

Answer №1

Our buddy @Archer mentioned in the comments to pass the client.id to the function setClientInfo, and within that function, locate the required client based on that id. Utilize the code snippet below for assistance.

let clients = [{
  "id": 1,
  "first_name": "Felipe",
  "last_name": "Aiken",
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd9b9c94969893cdbdcecbcdd39e93">[email protected]</a>",
  "gender": "Male",
  "ip_address": "13.189.73.39"
}, {
  "id": 2,
  "first_name": "Renell",
  "last_name": "Andreone",
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abd9cac5cfd9cec4c5ce9aebc3c2d8dfcadfd885c8c4c6">[email protected]</a>",
  "gender": "Female",
  "ip_address": "196.153.244.124"
}];

clients.forEach(function(client) {
    let tbody = document.querySelector('tbody');
    let newObj = {
        'name': 'client.first_name'
    };
    tbody.innerHTML = tbody.innerHTML + '\
        <tr>\
            <td>' + client.id + '</td>\
            <td>' + client.first_name + '</td>\
            <td>' + client.last_name + '</td>\
            <td>' + client.email + '</td>\
            <td>' + client.gender + '</td>\
            <td><button onclick="setClientInfo(' + client.id + ')" class="btn btn-primary">View</td>\
        </tr>\
    ';
});

function setClientInfo(clientId){
  console.log(clientId)
  var client = clients.find(x => x.id == clientId);
  console.log(client)
}
<table>
  <tbody></tbody>
</table>

A different approach could involve constructing elements without using a string and appending them via innerHTML. Instead, create the element directly using document.createElement(), then assign the listener by passing the object as a parameter. See example below:

let clients = [{
      "id": 1,
      "first_name": "Felipe",
      "last_name": "Aiken",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c2c5cdcfc1ca94e49792948ac7ca">[email protected]</a>",
      "gender": "Male",
      "ip_address": "13.189.73.39"
    }, {
      "id": 2,
      "first_name": "Renell",
      "last_name": "Andreone",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e092818e8492858f8e85d1a088899394819493ce838f8d">[email protected]</a>",
      "gender": "Female",
      "ip_address": "196.153.244.124"
    }];

    clients.forEach(function(client) {
        let tbody = document.querySelector('tbody');
        let newObj = {
            'name': 'client.first_name'
        };
        var trElem = document.createElement("tr");

        // LOOP THROUGH ALL CLIENT PROPERTIES
        for (var prop in client){
            var tdElem =  document.createElement("td");
            tdElem.textContent = client[prop];
            trElem.append(tdElem);            
        }      

        // Create the last td with the Button
        var tdClick = document.createElement("td");
        var btn = document.createElement("button")
        tdClick.append(btn);
        btn.onclick = setClientInfo.bind(this, client);
        btn.className = "btn btn-primary";
        btn.textContent = "View";
        trElem.append(tdClick);
        
        // Append to table body
        tbody.append(trElem);
    });

    function setClientInfo(client){
      console.log(client);
    }
<table>
  <tbody></tbody>
</table>

Answer №2

When the onclick handler is rendered as a string in HTML, an object literal is usually displayed as [object Object]. You can test this by running the following code in the developer console:

"" + {key: "value"}

The result will look like:

<button onclick="setClientInfo([object Object])" />

This type of handler is not valid JavaScript and will trigger an error. If you insist on including an object value inline in your HTML, you can convert the object to a string like this:

let newObj = "{'name': 'client.first_name'}";

Then your handler will appear as:

<button onclick="setClientInfo({'name': 'client.first_name'})" />

However, it's generally not recommended. It's better practice to just pass an identifier to the click handler function and use that to locate the necessary object in your JavaScript code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on showcasing a MultiPolygon GeoJSON on a Leaflet map

I am attempting to showcase a GeoJSON MultiPolygon object on a Leaflet map. I retrieve it from a PostgreSQL database as JSON and transform it into GeoJSON. I have validated the MultiPolygon object on GeoJSONLint and it checks out: However, I am facing di ...

What is the maximum number of JSON responses that can be handled by AJAX?

Upon entering the site, I am attempting to receive a JSON as an AJAX response. However, I am curious if there is a limit to the size of the object I can retrieve - whether through a GET or POST request? $http({ method: 'POST', url: &apos ...

Adjusting image dimensions dynamically using JavaScript based on screen size

My bootstrap setup seems to be causing issues when using the @media (min-height: 1000px) rule as the image class does not respond as expected. I am looking to implement a JavaScript solution that will automatically resize images once the screen height exc ...

Can a function be invoked using a variable as a parameter in JavaScript?

Imagine a scenario where the need arises to use a conditional statement that performs the same action but calls a different method. const c = true; // just for illustration let b = ''; if (c) { b = 'method1'; } else { b = 'met ...

When the audio on the device is in use, the video will not play and vice versa

Whenever my video starts playing, the audio from my device (such as iPod or Spotify) stops. If I try to play the audio manually while the video is playing, the video freezes. Interestingly, when I tested playing an audio file directly within the app, it wo ...

Establish Mongoose query requirement according to the property of the document

Presently, I have a Mongoose Event document with attributes like startTime, endTime, and duration. In my node.js file, I am working on executing a query that fetches all Events where the start time is earlier than the current timestamp, and the end time is ...

Alert function or append method is not functioning properly on the Document Object Model (DOM

Check out this code snippet on https://jsfiddle.net/safron6/9g98j68g/embedded/result/ I'm attempting to retrieve the calculated result from a list of APIs and JSON code that displays the precipIntensity. Even though the code executes in Firebug, the ...

What is the process for obtaining a page slug within the app directory of Next.js?

How to retrieve the slug of the current page in Next.js 13, as compared to Next.js 12 where it was done in a getStaticProps method? ✅Next.js 12 export async function getStaticProps(context) { const slug = context.params.slug } ❌Next.js 13 - Using t ...

Tips on creating a parameterized SQL query within Javascript

Does anyone know how to properly write a parameterized SQL Query in javascript? I attempted it myself, but encountered an error. I even tried another method, yet I'm still facing syntax errors. let sql =select * from q_users where firstname=?,[${na ...

Is it possible to identify when text has been successfully rendered using Javascript and SVG?

My svg elements are generated dynamically based on the text in an input field. Each break signifies a new group element structured like this: <g> <svg> <text/> <rect/> </svg> </g> I also have an option t ...

JavaScript Algorithm for Pyramids

Experimenting with simple algorithms brought me to this code. I'm curious if anyone has a more concise version in JavaScript for displaying a pyramid: const max= 30; let row = 1; for (let i = 1; i < max; i += 2) { console.log(' '.r ...

Sending an Array from Javascript to Node.js

First off, I want to express my gratitude for attempting to assist me. I am inquiring about how to pass an Array from JavaScript to a Node.js backend for parsing. Below is the Array in question: var Coordinates = [ {lat: 37.772, lng: -122.214}, ...

Ways to permanently change a javascript array object

I am facing an issue with my object array in the store file of my app, which I'm using MobX for. Whenever I try to modify or add to an object in the array, the data gets deleted upon refreshing the page. Is there a way to make these changes to the obj ...

How can I incorporate the "onClick()" function within an ajax call, while still utilizing the data returned in the success message?

After successfully making an Ajax call, I would like to implement an on-click function while still utilizing the original data retrieved. $.ajax({ URL: ......, type: 'GET', success: function (res) { var Ob ...

Attempting to replicate the functionality of double buffering using JavaScript

In my HTML project, I have a complex element that resembles a calendar, with numerous nested divs. I need to refresh this view in the background whenever there are updates on the server. To achieve this, I set up an EventSource to check for data changes on ...

Listing Field Names in Swagger

After doing some research online, I was able to understand how to utilize the enum tag in a swagger doc to define a list of possible values for a field. However, my current API requires a list of potential fields, each with a string value. Specifically, I ...

Angular: A guide to binding to the required/ngRequired attribute

There is a directive that may or may not be required, and it can be used in two different ways. <my-foo required></my-foo> or <my-foo ng-required="data.value > 10"></my-foo> Even though require and ngRequire are essentially t ...

Issue retrieving data from JSON in Android app

Every time I attempt to make a service call in order to extract data from a Google spreadsheet, the JSON response is null. Any thoughts on why this might be happening? Main Activity private static final String url = https://docs.google.com/spreadsheets/d ...

Maintain your position on the current page when refreshing Angular 4

My Anuglar 4 application features multiple routes, with two main ones being Logging and List of items. Specifically, the routes are http://localhost:4200/#/ and http://localhost:4200/#/items. However, I've noticed that when I reload the page while on ...

Guidelines for retrieving specific json information using PHP

Hello there, I am currently retrieving data directly from an API endpoint. While I was successful in obtaining the id, I am facing difficulty in accessing the "type":"participant" part, specifically the skillTier. Even though I have written the following ...