• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

168
Vistas
How to generate array of object from object

I have an object like this:

{
   name: 'ABC',
   age: 12,
   timing: '2021-12-30T11:12:34.033Z'
}

I want to make array of object of each key of above object like this:

[
   {
      fieldName: 'name',
      dataType: 'string'
   },
   {
      fieldName: 'age',
      dataType: 'number'
   },
   {
      fieldName: 'timing',
      dataType: 'date'
   }
]

I tried this:

let op = Object.entries(data).map(([key, value]) => ({
            fieldName: key,
            dataType: typeof value
        }));

but getting dataType: 'object' for date column but not able to achieve it. Is there any solution? Thanks in advance.

almost 3 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use date parse to check is a valid date or not.

const input = {
  name: 'ABC',
  age: 12,
  timing: '2021-12-30T11:12:34.033Z'
};

const output = Object.entries(input).map(([key, value]) => ({
  fieldName: key,
  dataType: typeof value === 'string' && !isNaN(Date.parse(value)) ?  'date':typeof value
}));

console.log(output);

almost 3 years ago · Juan Pablo Isaza Denunciar

0

You could use Object#entries with Array#map and typeof to the get the type of the value. For the case where 'date' must be used for valid time stamps, you could use Date.parse() method with Number#isNaN.

Try the following

const input = {
  name: 'ABC',
  age: 12,
  timing: '2021-12-30T11:12:34.033Z'
};

const output = Object.entries(input).map(([key, value]) => ({
  fieldName: key,
  dataType: typeof value !== 'string' || isNaN(Date.parse(value)) ? typeof value : 'date'
}));

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Edit: Replace Object#values with Object#entries.

Edit 2: Add typeof value !== 'string' for dataType condition. Borrowed from @RahulSharma's answer.

almost 3 years ago · Juan Pablo Isaza Denunciar

0

You can use Object.keys() and Array.prototype.map():

const ip = {
  name: 'ABC',
  age: 12,
  timing: '2021-12-30T11:12:34.033Z'
};

const op = Object.keys(ip).map((key) => ({
  fieldName: key,
  dataType: typeof ip[key] === 'string' && !isNaN(Date.parse(ip[key])) ? 'date' : typeof ip[key]
}));

console.log(op);

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda