0

My web service returns objects with single-letter property names. Because I want to use readable properties in my JavaScript code, I usually do a procedure similar to this:

$.getJSON('bla').done(res => {
  myResult = {
    hello: res.h,
    world: res.w
  };
});

Or

$.getJSON('bla').done(res => {
  res.hello = res.h; delete res.h;
  res.world = res.w; delete res.w;
  myResult = res;
});

An additional problem is, that I have to repeat that procedure the other way around, when I want to call back that object to the server.

Therefore my question is, if there is some kind of a simplified, bi-directional mapper method, or something like an implicit cast operator.

André Reichelt
  • 1,484
  • 18
  • 52
  • @mplungjan Can you give ma an example, please? – André Reichelt Oct 11 '19 at 08:13
  • 1
    Why don't you fix your web service to use meaningful property names? – Andreas Oct 11 '19 at 08:14
  • And based on your code I think you should have a look at: [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Oct 11 '19 at 08:16
  • @Andreas Thank you for your hint. I just made a minimal example. I know, that this code makes no sense in a real-world environment. – André Reichelt Oct 11 '19 at 08:23

1 Answers1

1

Here's one option, using two arrays of keys that map to each other, and a helper function that transforms an object with one of those key sets into an object with the other key set:

const transformObj = (obj, from, to) => Object.fromEntries(
  from.map((fromKey, i) => [to[i], obj[fromKey]])
);

const short = ['a', 'b', 'c'];
const long = ['aaa', 'bbb', 'ccc'];

console.log(transformObj({ a: 'foo', b: 'bar', c: 'baz' }, short, long));

console.log(transformObj({ aaa: 'zzz', bbb: 'yyy', ccc: 'xxx' }, long, short));

That said, this feels like an X/Y problem. It introduces unnecessary complication and very short properties arguably make things more difficult to read. I'd consider having your backend send an object that doesn't require transformation later, for the sake of consistency.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320