What is the reason behind getting `[Object object] [ Object object]` when you perform `{} + {}` in JavaScript?

I am just starting to learn JS and I'm puzzled by a situation. Let's consider the following code snippet:

var ids = [10,20,30];
var types= ['PIZZA','HAMBURGER','AVOCADO'];
var payload=[];

for(let i = 0; i <= ids.length; i++){
    var id= ids[i];
    var type= types[i];
    var couple= {"id":id ,"type":type};
    console.log(couple);
    payload.push(couple);}
           
console.log('result is ' + payload);

The output shows: [object Object],[object Object],[object Object],[object Object]

My expectation was something like :

{ "id" : 10, "type" : "PIZZA" },
{ "id" : 20, "type" : "HAMBURGER" },
{ "id" : 30, "type" : "AVOCADO" }

Why does {} + {} result in "Object object][Object object"? Could you please provide some insight on how to prevent this in JS?

Thank you for your time and looking forward to some helpful feedback! Wishing you a wonderful day!

Answer №1

Since JavaScript is weakly typed, a string + object operation will result in the object being converted to a string. To achieve the desired outcome, you should use `console.log('the result is', payload)

var ids = [10,20,30];
var types= ['PIZZA','HAMBURGER','AVOCADO'];
var payload=[];

for(let i = 0; i <= ids.length; i++){
    var id= ids[i];
    var type= types[i];
    var couple= {"id":id ,"type":type};
    payload.push(couple);}
           
console.log('result is ', payload);
console.log('object to string', payload.toString())

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

I encountered an issue while attempting to utilize a JavaScript script - I received an error message stating "Uncaught ReferenceError: jQuery is not defined."

Currently, I am utilizing a template with multiple pages and I need to use one of them. I followed all the necessary steps correctly, but I encountered an error in the console that says Uncaught ReferenceError: jQuery is not defined. Below is my HTML scrip ...

Tips for activating the default 500 error page in Next.js

I'm having trouble getting Next.js to display its default 500 error page. While most sources discuss creating a custom error page, the Next.js documentation only briefly references their built-in 500 error page. I want the default page to show up when ...

Strategies for preserving context throughout an Ajax request

In my project, I am looking to implement an Ajax call that will update a specific child element within the DOM based on the element clicked. Here is an example of the HTML structure: <div class="divClass"> <p class="pClass1">1</p> &l ...

What is the best way to verify if a value matches the container ID in Vue?

I am trying to create a condition where a property is checked against the ID of a div container. If they match, I want to display the container. For example, in the code snippet below, I need to compare the activeWindow property with the div id. If they a ...

Exploring the iteration process of a JavaScript array with Node-API

Currently, I am in the process of developing a Node.js addon utilizing Node-API. My algorithm takes a Javascript array as input, processes it within the addon, and then returns the result. For implementing any logic on the array, I need to iterate through ...

Retrieve all Tableau workbooks stored on the server

I am currently working with Tableau Server and have multiple workbooks published on it. My goal is to create a dropdown list that displays all the workbook names along with their corresponding URLs. This way, when a user selects a value from the dropdown, ...

I am experiencing difficulty with the display of the elements within my <li></li> tags on both the browser and in the inspect elements section. Strangely, only my <ol> tags are showing up properly

I'm having trouble with the display of elements in my list items () on the browser. When I inspect the page, only the paragraph tags show up and the total value is also not being displayed. However, I can see the items in the birdInCart array when I c ...

Improving the speed of the autocomplete feature involves optimizing the parsing of a substantial JSON file during every ajax call

I'm working on creating an autocomplete feature for cities and zip codes using Rails 4 and jQuery UI. I have a sizable JSON file with around 500,000 lines containing an array (cp_autocomplete) of zip codes (CP) and cities (CITY). Currently, my autoco ...

Leverage ActiveModel::Serializers for incorporating two primary JSON arrays

I am attempting to send my front-end application JSON data structured like this: { facilities: [ {id: 5, name: 'Happy Days Ranch', location: { address: '1424 Pastoral Lane', zipcode: '25245'}, instructor_ids: [2, 4, 9] ...

Having trouble successfully sending a variable through a JavaScript form

Within my HTML file, I have a form with various input fields and radio buttons that allow users to enter search parameters. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href='https:// ...

Vue3 - changes to array data not triggering automatic re-rendering

Being relatively new to Vue, I'm struggling to automatically update the array in my project. My webpage is simple - it consists of an input field and a button. When the button is clicked, the data is saved in a MongoDB database through my server. Be ...

Loading FBX files with Textures in Three.js

After obtaining a fbx file with textures from this link, I attempted to open it using three.js: var loader = new THREE.FBXLoader(); loader.load('models/fbx/myfile.fbx', function(object) { scene.add(object); }, (ev) => { console.log(e ...

Adding icons to form fields based on the accuracy of the inputs provided

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Assignment 2 - Website Bui ...

Incorporating a computed variable in a v-select within a VueJs endless loop

I've been attempting to utilize a computed value in a v-select component from Vuetify, but every time I select an item, it triggers an endless loop. To demonstrate the issue, I have recreated my code in this CodePen. Please be cautious as it may caus ...

Exploring content in Embed message fields

Can anyone help me with logging the contents of an embed received from a specific bot? I've tried some basic things but seem to be missing something. Please review my code and let me know what I'm doing wrong and how I can improve it. Thank you i ...

Is it possible to trigger an AJAX validation only after the jQuery validation plugin has successfully validated the input?

I utilized the jQuery validation plugin for form field validation. The goal now is to send an ajax request only when the fields are deemed valid by the jQuery validation plugin. JavaScript: $(function(){ $("#form").validate({ errorPlacement: ...

Retrieving an Enum member based on its value in TypeScript

I am working with an enum called ABC: enum ABC { A = 'a', B = 'b', C = 'c', } In addition, I have a method named doSomething: doSomething(enum: ABC) { switch(enum) { case A : console.log(A); break; case ...

Sending a XML file from a Vue application to an ASP.NET Core backend using axios

I'm encountering difficulties when trying to upload an xml file using axios to my asp .net server. Below is the code snippet I am using on the vue side to retrieve and upload the xml file: uploadXmlFile(file: any) { const rawFile = new XMLHttpRequ ...

I'm encountering a persistent issue of receiving null when attempting to read a JSON object file in

Every time I attempt to read, the result is always null. This pertains to a json file. { "team": { "name": "john 1", "id": "12345" } } I am attempting to accomplish this using POJO. public class Team { private String name; private ...

Save room for text that shows up on its own

I am currently dealing with a situation where text appears conditionally and when it does, it causes the rest of the page to be pushed down. Does anyone know the best way to reserve the space for this text even when it's not visible so that I can pre ...