簡體   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