Home > front end >  Why In JS -> {} {} gives [Object object] [ Object object]?
Why In JS -> {} {} gives [Object object] [ Object object]?

Time:10-23

I am new to JS and I'd like to know why I am facing this situation. Let's assume we have something like this :

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);

result is : [object Object],[object Object],[object Object],[object Object]

I was expecting something like :

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

Do you know why {} {} gives "[Object object][Object object]" ? can you please explain to me how can I avoid this in JS?

Thank you as always for your time, waiting for some cool feedback! have a great day!

CodePudding user response:

With Js being weakly typed, string object will convert the object to a string. What you want to do is `console.log('the resulst 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())

  • Related