Convert record type to JS object


#1

Hi all

How to convert a record typed value into JS object. For example:

type coin = {
  amount: float,
  currency: string,
};

let c: coin = {
  amount: 34.454,
  currency: "FFF",
}

Or how to create a JS object in reasonml?

Thanks


#2

For simplest object with plain data you can use this https://bucklescript.github.io/docs/en/generate-converters-accessors.html#convert-between-jst-object-and-record

If you have nested objects you can use Js.Json module, but it is not that easy. Here you can find two libraries to help with it https://bucklescript.github.io/docs/en/json.html#higher-level-helpers.

What here is called Json is actually plain untyped js data, rather than json-string.


#3

In addition to what @Ebuall suggested, you can also manually write a converter:

let coinToJs = ({amount, currency}) => {
  "amount": amount,
  "currency": currency,
};

let cJs = coinToJs(c);

The syntax for creating a JS object in Reason is: {"field1": val1, ..., "fieldN": valN}.


#5

First of all, thanks so much for answer.

But how to convert:

[@bs.deriving {jsConverter: newType}]
type coin = {
  amount: float,
  currency: string,
};

type coins = array(coin); 

into JS array?

thanks


#6
let a = [| c1, c2, c3 |];
let b = Array.map(coinToJs, a);

#7

Awesome. Thanks a lot.