Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda