ThisaruG
ThisaruG

Reputation: 3412

Map the Rest Fields when Data Mapping from One Record to Another in Ballerina

I have a record type Foo which is an open record, with a set of defined fields. I have another record Bar which is also an open record, with a set of defined fields. I need to map data from Foo to Bar like this:

type Foo record {
    string fs;
    int fi;
};

type Bar record {
    string bs;
    int bi;
};

function transform (Foo foo) returns Bar => {
    bs: foo.fs,
    bi: foo.fi
}

How can I map the rest fields from Foo to Bar? I don't need to change the rest field names, but to map them as it is.

Upvotes: 1

Views: 97

Answers (1)

LochanaJ
LochanaJ

Reputation: 144

Can't think of a direct syntax. You could do something like this though.

public function main() {
    Foo foo = {fs: "hello", fi: 42, "a": 1, "b": true, "c": "cat"};
    Bar bar = {bs: foo.fs, bi: foo.fi};

    foreach string k in foo.keys() {
        if k != "fs" && k != "fi" {
            bar[k] = foo[k];
        }
    }
    io:println(bar);
}

transform() function would look like this.

function transform(Foo foo) returns Bar {
    Bar bar = {bs: foo.fs, bi: foo.fi};
    foreach string k in foo.keys() {
        if k != "fs" && k != "fi" {
            bar[k] = foo[k];
        }
    }
    return bar;
};

Upvotes: 1

Related Questions