繁体   English   中英

展平对象属性列表

[英]Flattening a list of object properties

经过多年的命令式思维方式,我发现很难以函数式风格编写此代码。

给定一个输入,如:

[{'id': 'foo', frames: ['bar', 'baz']}, {'id': 'two', frames: ['three', 'four']}]

输出应该是:

[ { foo: 'bar' }, { foo: 'baz' }, { two: 'three' }, { two: 'four' } ]

如何在 javascript 中以函数式风格编写此代码?

首先让我们创建一个函数,它给定一个对象返回一个帧数组:

function toFrames(obj) {
    var id = obj.id;

    return obj.frames.map(function (frame) {
        var obj = {};
        obj[id] = frame;
        return obj;
    });
}

接下来我们创建一个concat函数:

function concat(a, b) {
    return a.concat(b);
}

最后我们进行转换:

var input = [{
    id: "foo",
    frames: ["bar", "baz"]
}, {
    id: "two",
    frames: ["three", "four"]
}];

var output = input.map(toFrames).reduce(concat);

自己看演示:

 var input = [{ id: "foo", frames: ["bar", "baz"] }, { id: "two", frames: ["three", "four"] }]; var output = input.map(toFrames).reduce(concat); alert(JSON.stringify(output, null, 4)); function toFrames(obj) { var id = obj.id; return obj.frames.map(function (frame) { var obj = {}; obj[id] = frame; return obj; }); } function concat(a, b) { return a.concat(b); }

函数式编程是不是很有趣?


一个解释:

  1. toFrames函数接受一个对象(例如{ id: "foo", frames: ["bar", "baz"] } )并返回框架对象列表(即[{ foo: "bar" }, { foo: "baz" }] )。
  2. concat函数只是连接两个数组。 .reduce .reduce(concat)方法调用 flatttens 数组,如[[a,b],[c,d]][a,b,c,d]
  3. 给定输入的对象列表,我们首先将每个对象转换为框架列表,从而生成框架对象列表。
  4. 然后我们展平嵌套列表以产生所需的输出。

简单的。

假设arr是输入,您可以这样做

result = []; // array
arr.forEach(function(o) { // go through elements
    for (var i = 0; i < o.frames.length; i++) { // make a since we need to get two objs per element
        var obj = {}; // an object which will be over written for every iteration
        obj[o.id] = o.frames[i]; // set property name and value
        result.push(obj); // finally push it in the array
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM