Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda