What is the significance of the term "Object object"?

I am new to javascript and encountering an issue. When I use alert in my script, the output data is shown as [Object object]. The function below is called when the button (onClick) is clicked. There are [Object object] elements in the array. The last line of code, specifically innerHtml, is not functioning properly.

<!DOCTYPE HTML>
<html>

<head>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div class="center">
    <h1 align="center">Shop Basket</h2>
      <script type="text/javascript" src="external.js"></script>

      <table align="center">
        <tr>
          <th align="left">Price</th>
          <th>Product</th>
          <th></th>
        </tr>
        <script>
          let products = [{
              20: "ssd drive"
            },
            {
              1100: "washing machine"
            },
            {
              219: "tablet"
            },
            {
              500: "monitor"
            },
            {
              789: "i5 processor"
            },
            {
              88: "sound card"
            },
            {
              220: "logitech mouse"
            },
            {
              219: "modecom keyboard"
            },
            {
              900: "gtx 1060"
            },
            {
              823: "rx 570"
            }
          ];
          let shopBasket = [];

          function addToBasket(value) {
            shopBasket.push(value);
            alert(shopBasket);
            document.getElementById("change").innerHtml = "" + shopBasket.length;
          }
          for (let i = 0; i < products.length; i++) {
            for (let key in products[i]) {
              document.write("<tr>");
              document.write("<td>" + key + "</td>");
              document.write("<td>" + products[i][key] + "</td>");
              document.write('<td><input value="Add to ShopBakset" type="button" onClick="addToBasket(\'' + products[i] + '\')"/></td>');
              document.write("</tr>");
            }
          }
        </script>

      </table>
      <center>
        <a href="html-link.htm"><img src="shopbasket.jpg" title="basket" alt="basket"></a>
      </center>
  </div>
  <p id="change"></p>
</body>

</html>

Best regards

Answer №1

If you want to include JSON stringify in your HTML file, you can do it like this:

document.write('<td><input value="Add to ShopBakset" type="button" onClick="addToBasket(\'' + JSON.stringify(products[i]) +'\')"/></td>');

To parse the JSON in your JS code, add the following:

shopBasket.push(JSON.parse(value));

You can test the difference by running the code snippet and comparing the console output with and without JSON.stringify:

let products = [ 
    {20: "dysk ssd"}, 
    {1100: "pralka"}, 
    {219: "pad"}, 
    {500: "monitor"},
    {789: "i5 processor"},
    {88: "soundblaster"},
    {220: "mysz logitech"}, 
    {219: "klawiatura modecom"},
    {900: "gtx 1060"}, 
    {823: "rx 570"}
];

for (let i = 0; i < products.length; i++) {
   for (let key in products[i]) {
      console.log('Without using stringifiy', '<td><input value="Add to ShopBakset" type="button" onClick="addToBasket(\'' + products[i] + '\')"/></td>');
      console.log('With using stringifiy', '<td><input value="Add to ShopBakset" type="button" onClick="addToBasket(\'' + JSON.stringify(products[i]) + '\')"/></td>');
   }

   // only showing the first element
   break;
}

If you parse the string again in your JavaScript function:

AddToBasket('{"20":"dysk ssd"}');

function AddToBasket(value) {
  let parsedBasket = JSON.parse(value);
  
  console.log(parsedBasket);
  
  // your code
}

Update: To resolve the unexpected token issue, move all the JavaScript code to an external file and add an ID to your table:

<table id="productsTable" align="center">

Then in the external JS file:

let table = document.getElementById('productsTable');

for (let i = 0; i < products.length; i++) {
    for (let key in products[i]) {
        table.innerHTML += "<tr>";
        table.innerHTML += "<td>" + key + "</td>";
        table.innerHTML += "<td>" + products[i][key] + "</td>";
        table.innerHTML += "<td><input value=\"Add to ShopBakset\" type=\"button\" onClick=\"addToBasket(" + formatProduct(products[i]) + ")\"/></td>";
        table.innerHTML += "</tr>";
    }
}

function formatProduct(product) {
   return JSON.stringify(product).replace(/\"/g, '\'')
}

In your addToBasket function, you can print the result to the console:

function addToBasket(value) { 
   console.log('json object', value);

   // ... your code
}

This will display the JSON object in the console.

https://i.stack.imgur.com/EWWNn.png

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

Activate on-demand static regeneration with Next.js

I am thoroughly impressed by the functionality of Incremental Static Regeneration in Next.js. However, I am currently seeking a method to manually trigger static page regeneration as needed. It would be ideal to have a command that can be executed via an ...

Retrieving JSON data to create and showcase an HTML table

Can you help me figure out what's going wrong with my code? I have an HTML page with a table where I fetch data from the web in JSON format using JavaScript. The logic works perfectly when the fetch code is let to run on its own, but when I try to ex ...

"Is it possible to access variables declared in the main app.js file from separate route files in Node.js Express 2.5.5 and if so

Recently, I've started using the latest version of Express (2.5.5) which now automatically creates a ./routes directory in addition to ./views and ./public In the routes directory, there is an index.js file that includes: /* * GET home page. */ e ...

Step-by-step guide on triggering a button using another button

I have a unique question that sets it apart from others because I am looking to activate the button, not just fire it. Here is my syntax: $("#second_btn").click(function(){ $('#first_btn').addClass('active'); }) #first_btn ...

Manipulating an element in the JSON data is causing alterations to the preceding elements

I am facing a challenge with two JSON arrays. $scope.arr1 = [ { "id": 1, "first_name": "Philip", "last_name": "Kim", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6e7577732e5e737b7a777f78776c7b307d717 ...

Learn how to efficiently pass multiple props using a loop in Vue

I am dealing with an object that has multiple properties. Typically, I know which props I want to pass to my component and do it like this: <component :prop1="object.prop1" :prop2="object.prop2" :prop3="object.prop3" /> However, I want to pass the ...

Sending an array of JSON objects using jQuery is a simple and straightforward process. By

I'm currently facing a challenge while working on my web page - I am struggling to send an Array of JSON objects to my PHP backend script. Below is the JavaScript code I have been using (with jQuery): var toSend = new Array(); ...

Struggling to deal with conditionals in Express

Just starting with Express and I've come across the following code: const { response } = require("express"); const express = require("express"); const app = express(); app.get("/api/products/:id", function (req, res) { ...

Leveraging two AJAX requests within a single function

I am working on creating an ajax function to post data that I've retrieved using another ajax function. While I have figured out how to use a callback function, I am struggling with passing the data from one function to the other. Here is what I have ...

Implement a click event using jQuery specifically for Internet Explorer version 7

How can I add an onclick attribute using jQuery that is compatible with IE7? So far, the following code works in browsers other than IE8 and Mozilla: idLink = Removelst(); var newClick = new Function(idLink); $(test1).attr('onclick', null).clic ...

Checking the response from an AJAX call with an if/else statement

Is there a way to create a counter for unread messages using PHP and jQuery? Below is the PHP code in BubbleStat.php: $totalMsg = $mysql->totalRows("SELECT msg_id from messages WHERE msg_opened = 0 AND msg_receiver = '".$_SESSION["ActiveUserSessio ...

A guide on how to implement promise return in redux actions for react native applications

I'm using redux to handle location data and I need to retrieve it when necessary. Once the location is saved to the state in redux, I want to return a promise because I require that data for my screen. Here are my actions, reducers, store setup, and ...

After receiving a data token from the server in one controller, how can I efficiently utilize that token in a different AngularJS controller?

In my adminSearchCtrl controller, I am receiving data from the server in the form of a token and want to pass that token to another controller named "adminViewCtrl". How can I achieve this? adminSearchCtrl.js $scope.getUserDetails = function(selectedUser ...

Using Nuxt.js to import custom NPM packages on a global scale

The installation process for Nuxt's plugins/modules system can be quite intricate. Despite attempting to follow various suggestions, I have struggled to accomplish a seemingly simple task. After installing the NPM package csv-parse (which can be found ...

Is there a glitch in the Selenium Java CSS Selector functionality?

Everything seems to be working smoothly with that code! It successfully locates and clicks on my button within the span tag. driver.findElement(By.cssSelector("span[id$=somePagesCollection] a")).click(); However, after clicking the button, an input field ...

When the progress bar is clicked, the background color changes and then changes back again

https://www.w3schools.com/code/tryit.asp?filename=FG1ZE0NJ4ZX7 https://i.stack.imgur.com/Bnd0k.png I have created a progress bar that resembles the screenshot provided. When I hover over it, the color changes to green. However, I am looking for assistanc ...

Detecting single letters in a sentence and changing their appearance using CSS

Looking to make a subtle change to text? I need to swap out single letters in a passage (I have a cat that ate a fish). Any ideas on how to do this? The goal is to input a block of text into a textbox, then display it in a div. I've had difficulty fi ...

Stop options from being hidden in a select dropdown using HTML

Can I keep the options visible when a user selects an item in the 'select' dropdown? I want to add more options to the 'select' when the user clicks on the 'op2' item, without closing the list of options. <select> <o ...

Sort through the array using a separate array in Vuejs

I am currently working with two arrays: { "products": [ { "name": "Jivi", "Hint": "45-60 IE/kg alle 5 Tage\n60 IE 1x/Woche\n30-40 IE 2 x/Woche", "frequency": ["1", "2", "8"] }, { "name": "Adynovi", ...

Methods like jQuery blink(), strike(), and bold() offer dynamic ways to manipulate

I'm currently tackling an inquiry. The code I crafted seems to be functioning without any issues: (function () { if($('#target:contains("bold")')) { $('#target span:first').css('font-weight','bold ...