[英]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:一个解释:
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" }]
)。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]
。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.