[removed] Determine unknown array length and map dynamically

后端 未结 5 745
深忆病人
深忆病人 2021-02-08 11:01

Going to do my best at explaining what I am trying to do.

I have two models, mine and an api response I am receiving. When the items api response comes in, I need to map

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-08 11:25

    As mentioned in the comments, there is no strict definition of the input format, it is hard to do it with perfect error handling and handle all corner cases.

    Here is my lengthy implementation that works on your sample, but might fail for some other cases:

    function merge_objects(a, b) {
        var c = {}, attr;
        for (attr in a) { c[attr] = a[attr]; }
        for (attr in b) { c[attr] = b[attr]; }
        return c;
    }
    
    
    var id = {
        inner: null,
        name: "id",
        repr: "id",
        type: "map",
        exec: function (input) { return input; }
    };
    
    // set output field
    function f(outp, mapper) {
        mapper = typeof mapper !== "undefined" ? mapper : id;
        var repr = "f("+outp+","+mapper.repr+")";
        var name = "f("+outp;
        return {
            inner: mapper,
            name: name,
            repr: repr,
            type: "map",
            clone: function(mapper) { return f(outp, mapper); },
            exec:
            function (input) {
                var out = {};
                out[outp] = mapper.exec(input);
                return out;
            }
        };
    }
    
    // set input field
    function p(inp, mapper) {
        var repr = "p("+inp+","+mapper.repr+")";
        var name = "p("+inp;
        return {
            inner: mapper,
            name: name,
            repr: repr,
            type: mapper.type,
            clone: function(mapper) { return p(inp, mapper); },
            exec: function (input) {
                return mapper.exec(input[inp]);
            }
        };
    }
    
    // process array
    function arr(mapper) {
        var repr = "arr("+mapper.repr+")";
        return {
            inner: mapper,
            name: "arr",
            repr: repr,
            type: mapper.type,
            clone: function(mapper) { return arr(mapper); },
            exec: function (input) {
                var out = [];
                for (var i=0; i

提交回复
热议问题