[英]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); }
函數式編程是不是很有趣?
一個解釋:
toFrames
函數接受一個對象(例如{ id: "foo", frames: ["bar", "baz"] }
)並返回框架對象列表(即[{ foo: "bar" }, { foo: "baz" }]
)。concat
函數只是連接兩個數組。 .reduce .reduce(concat)
方法調用 flatttens 數組,如[[a,b],[c,d]]
到[a,b,c,d]
。簡單的。
假設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.