Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Push an object into an array inside an object

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!