Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!