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

124
Vistas
Prevent node.js from converting a nested object with numeric keys into array

When i have an object with a nested object within, whose keys are numbers and send it to my node.js server, then the nested object is converted to an array. How can i prevent this ?

Client:

$.ajax({
    url : `/cctool/report`,
    method : "PUT",
    data : {
        new : {
            10 : "Test",
            20 : "Hello",
        }
    }
});

Server:

router.put("/cctool/report", (request, response) => {
    console.log(request.body);
}

{ new: [ 'Test', 'Hello' ] }

When i add a not numeric key, everything works fine. Also when the keys are at the first level.

My settings:

const express = require('express');
const CookieParser = require('cookie-parser');
const Sessions = require('express-session');
const crypto = require('crypto');
const router = express.Router();

router.use(express.json());
router.use(express.urlencoded({extended : true}));
router.use(CookieParser());
router.use( Sessions({
    secret : crypto.randomBytes(64).toString('hex'),
    saveUninitialized : false,
    cookie : {maxAge : 1000 * 60 * 60 * 8},     // 8 hours
    resave : false
}));
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try adding the contentType header and using JSON.stringify to serialize the object before passing to $.ajax:

const express = require("express");
const app = express();

const html = `<!DOCTYPE html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
</head>
<body>
<script>
$.ajax({
  url: "/cctool/report",
  method: "PUT",
  contentType: "application/json",
  data: JSON.stringify({
    new: {
      10: "Test",
      20: "Hello",
    }
  }),
  success: data => console.log(data),
});
</script></body></html>`;

app
  .use(express.json())
  .get("/", (req, res) => res.send(html))
  .put("/cctool/report", (req, res) => {
    console.log(req.body);
    res.json(req.body);
  })
  .listen(3000);

See jQuery posting JSON.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You have to use a String value as a key, if you want to use a number you have to convert it to String type. Source: https://tc39.es/ecma262/#sec-object-type

data : {
        new : {
            "10" : "Test",
            "20" : "Hello",
        }
    }
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