简体   繁体   English

展平对象属性列表

[英]Flattening a list of object properties

I'm finding it difficult to write this code in a functional style after years of working with an imperative mindset.经过多年的命令式思维方式,我发现很难以函数式风格编写此代码。

Given an input like:给定一个输入,如:

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

The output should be:输出应该是:

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

How would one write this in a functional style in javascript?如何在 javascript 中以函数式风格编写此代码?

First let's create a function which given an object returns an array of frames:首先让我们创建一个函数,它给定一个对象返回一个帧数组:

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

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

Next we create a concat function:接下来我们创建一个concat函数:

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

Finally we do the transformation:最后我们进行转换:

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

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

See the demo for yourself:自己看演示:

 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); }

Isn't functional programming fun?函数式编程是不是很有趣?


An explanation:一个解释:

  1. The toFrames function takes a object (for example { id: "foo", frames: ["bar", "baz"] } ) and returns the list of frame objects (ie [{ foo: "bar" }, { foo: "baz" }] ). toFrames函数接受一个对象(例如{ id: "foo", frames: ["bar", "baz"] } )并返回框架对象列表(即[{ foo: "bar" }, { foo: "baz" }] )。
  2. The concat function just concatenates two arrays. concat函数只是连接两个数组。 The .reduce(concat) method call flatttens arrays like [[a,b],[c,d]] to [a,b,c,d] . .reduce .reduce(concat)方法调用 flatttens 数组,如[[a,b],[c,d]][a,b,c,d]
  3. Given an input list of objects, we first convert each object into a list of frames, resulting in a list of list of frame objects.给定输入的对象列表,我们首先将每个对象转换为框架列表,从而生成框架对象列表。
  4. We then flatten the nested list to produce the desired output.然后我们展平嵌套列表以产生所需的输出。

Simple.简单的。

You can do it this way supposing arr is the input假设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