-1

First of all, I'm new in node js. I'm trying to create a REST API which looks like this:

 [{
 id: 1,
 name: 'tushar hasan',
 email: 'mtushar**@gmail.com',
 devices: {
        id: 2,
        device_mac: '4A:34:ER:34:12',
        relays: [
        {
           relay_name:"r1",
           status:0
        },
        {
           relay_name:"r2",
           status:1
        }
     ]
     }
 }]

But no matter what I'm trying it keeps on showing me below output:

[
   {
     id: 1,
     name: 'tushar hasan',
     email: 'mtushar**@gmail.com',
     devices: { 
               id: 2,
               device_mac: '4A:34:ER:34:12', 
               relays: [Array] 
             }
      }
   ]

I'm providing you source code that's in below:

var x = [];
var data = {id :1, name:'tushar hasan', email:'mtushar**@gmail.com'};

var relay1 = {relay_name:'r1', status:0};
var relay2 = {relay_name:'r2', status:1};

var devices = {id:2, device_mac: '4A:34:ER:34:12'};

devices.relays = [];
devices.relays.push(relay1);
devices.relays.push(relay2);
data.devices = devices;
x.push(data);
console.log(JSON.stringify(x));
console.log(x);

By the way, when I call JSON.stringify(x), it provides me elements inside the relay array property. But without JSON.stringify(x) it doesn't show the elements inside relay property.

Thanks in advance.

Héctor
  • 24,444
  • 35
  • 132
  • 243
Tushar Hasan
  • 55
  • 1
  • 1
  • 6
  • I don't see any problem there. It seems like the tool you use to see that does not show it to you right away – ilkerkaran Oct 20 '21 at 08:31

1 Answers1

0

Your code is fine. By default, when converting an object to string (like console.log does), the nested arrays will get converted to the text [Array]). The fact that you see the correct output when you call JSON.stringify asserts that it's really there.

Mureinik
  • 297,002
  • 52
  • 306
  • 350