且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用lodash根据类型对多个对象进行分组

更新时间:2023-11-26 10:45:58

您可以使用另一种方法,即复制每个对象leven并映射所有数组,并使用分组函数将最后一级分组.

You could use another approach by copying each object leven and map all arrays and group the last level by using a function for grouping.

此方法使用amit函数,该函数获取每个级别和起始对象的所有功能.

This approach uses am iter function which gets all functions for each level and the starting object.

最后,它将返回具有给定结构和分组项目的新对象.

At the end, it returnes a new object with the given structure and the grouped items.

function copy(source, fn) {
    return Object.assign({}, ...Object
        .entries(source)
        .map(([k, v]) => ({ [k]: fn(v) }))
    );
}

function map(array, fn) {
    return array.map(fn);
}

function group(array) {
    var items;
    return array.reduce((r, o) => {
        if (listItemTypes.includes(o.type)) {
            if (!items) {
                items = [];
                r.push({ type: 'list', items });
            }
            items.push(o);
        } else {
            items = undefined;
            r.push(o);
        }
        return r;
    }, []);
}

function iter([fn, ...fns], object) {
    return fn ? fn(object, iter.bind(null, fns)) : object;
}    

var object = { data: { areas: [{ sections: [{ rjf: [{ type: "unordered-list-item", text: "Item 1" }, { type: "unordered-list-item", text: "Item 2" }, { type: "paragraph", text: "This is text" }] }] }] } },
    listItemTypes = ['unordered-list-item', 'ordered-list-item'],
    result = iter([copy, copy, map, copy, map, copy, group], object);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }