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

Is e.preventDefault() failing to work in Next.js?

Hey everyone, I'm new to react.js and next.js. I attempted to copy some data from a form and display it in the console, but using e.preventDefault() is preventing me from submitting my form. Is there a more effective way to achieve what I'm aimin ...

Combining several JSON objects into a single JSON object using JavaScript

I am in need of merging JSON objects from various sources into a single JSON object using JavaScript. For example, I have two JSON objects with different values that I need to combine and add a new value to the final result. json1= { "b":"t ...

Discovering a specific URL link element within the DOM using webdriver.io

I am currently utilizing webdriver io for conducting tests on a webpage. I am in need of verifying the existence of an element with a specific href on the page. I have attempted to achieve this using the following snippet var client = webdriverio.remote ...

Issue: Bidirectional binding functionality is not functioning properly within the user interface modal

I'm currently working on displaying data in a modal, but I'm facing issues with getting two-way binding to work properly. In my HTML code: <div class="cta-actions"> <div class="action"><a class="btn btn-lg btn-max">Send a pa ...

Different time parameter for setting a timeout in Javascript

I am struggling to create a slideshow with varying time intervals for each image. My knowledge of Javascript is limited, and I have been working on resolving this issue for quite some time. /* function ShowEffect(element){ new Effect.Appear(element, ...

Stop the bubbling effect of :hover

How can the hover effect be prevented for the parent element when hovering over its children? Please take a look at the following code snippet: const parent = document.getElementById('parent') parent.onmouseover = function testAlert(e) { /* ...

What is the best way to display a chosen item in a text input field?

https://i.stack.imgur.com/Qe5Ds.png Looking to create a similar design, but lacking the necessary expertise. What steps should I take or what is the specific term for this style? Seeking assistance in implementing this using jQuery, PHP, or JavaScript. A ...

React-Native introduces a new container powered by VirtualizedList

Upon updating to react-native 0.61, a plethora of warnings have started appearing: There are VirtualizedLists nested inside plain ScrollViews with the same orientation - it's recommended to avoid this and use another VirtualizedList-backed container ...

site.js problem

Recently, I decided to create my very own CS:GO gambling website. After successfully setting it up on my localhost using VPS, I moved on to getting a domain and finalizing everything. However, when attempting to run site.js, an error message popped up: [e ...

Activate animation upon scrolling to specific element using Material-UI

Currently building out a website using react and Material-UI, I am looking to enhance the user experience with some transitions. At the moment, I have a button set up to display a component, but I want it to show up when I scroll to that specific part of ...

The variable from AJAX is not being displayed in PHP

Need help with transferring a JavaScript variable to the same PHP page. The following code is what I have so far: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script& ...

What are some effective ways to optimize a chat application and reduce the strain on the server?

I once created a Python app that allowed users to create chat rooms using a simple REST API server. The client would send requests to the server, which would then respond appropriately. These responses were received by a JavaScript client that continuous ...

What is the most effective approach for handling JSON data from URLs in a professional manner?

Hey there, I'm facing a dilemma on how to efficiently handle data retrieved from various URLs on my website. My website allows me to fetch JSON data from multiple URLs. For instance, there's a page full of posts related to a specific group with ...

Can users be prevented from bookmarking a particular web page?

I'm working on a Python (Django) webpage and I need to prevent users from being able to bookmark a certain page. Is there a way to do this? ...

Verify if a fresh message has been added using AJAX

Is it possible to create a notification system similar to Facebook, where the tab title displays the number of new messages without refreshing the entire page? Below is a snippet of code from my website's message box feature that I am working on. < ...

Assist me with Twitter

Seeking assistance with a coding issue related to displaying Twitter posts on a website. I have found a code snippet that accomplishes this: //Scrolling of tweets in the footer $(function () { var tweetVP = $("#footerTweetsViewport"); arrTweetNav ...

What is causing my Li elements to be unchecked in REACT?

Why is the 'checked' value not changing in my list? I'm currently working on a toDo app Here are my State Values: const [newItem, setNewItem] = useState(""); const [toDos, setToDos] = useState([]); This is my function: funct ...

Using the same ng-model to show distinct values in two separate input fields

I have a form with a dropdown list that loads data using the ng-model="placeid". When a user selects an option from the dropdown, I want to display the selected place's latitude (place.lat) in an input box. Here is the dropdown list code: <select ...

Exploring the animation potential of HTML5 canvas and Javascript through utilizing putImageData with animated gifs

I am interested in modifying the image data of each frame in an animated gif while it is playing in a web browser, using HTML5 canvas and Javascript. For instance, I would like to convert every frame to grayscale dynamically as the gif plays. Is this achie ...

What is the best way to use Javascript in order to automatically open a designated tab within SharePoint 2013?

Currently, I am in the process of developing a website project which incorporates Bootstrap tabs utilizing jQuery. While these tabs are functioning excellently on various pages, I am faced with the challenge of linking specific icons to corresponding tabs ...