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

158
Vistas
what's the best way to convert an array to an object with some special keys like x & y with typescript?

I just want to write a simple function which converts an array with 2 values [7, 9] to an object with x & y keys like : { x: 7, y: 9 }

interface coordinates {
  x: number;
  y: number;
}

function getAnObjectOfnum(arr: number[]): coordinates;
function getAnObjectOfnum(arg1: unknown, arg2?: unknown): coordinates {
  let coord: coordinates = {
    x: 0,
    y: 0,
  };
  if (Array.isArray(arg1)) {
    const converted = arg1.reduce((a, v, i) => ({ ...a, [i]: v }), {});
  }
  return coord;
}

console.log(getAnObjectOfnum([7, 9]));

That's my effort to find the solution.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I just want to write a simple function which converts an array with 2 values [7, 9] to an object with x & y keys like : { x: 7, y: 9 }

Unless there are requirements you're not describing in the question, it can be much simpler than that:

function getAnObjectOfnum(arr: [number, number]): coordinates {
    return {x: arr[0], y: arr[1]};
}

Playground link

Note that I've used [number, number] rather than number[], since we need exactly two values. This is a tuple type.

That can be made more concise using parameter destructuring, but possibly at the expense of clarity (or possibly not; if you're familiar with destructuring, it's clearer than I would have thought):

function getAnObjectOfnum([x, y]: [number, number]): coordinates {
    return {x, y};
}

Playground link

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