Home > Blockchain >  what's the best way to convert an array to an object with some special keys like x & y with typ
what's the best way to convert an array to an object with some special keys like x & y with typ

Time:09-26

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.

CodePudding user response:

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

  • Related