Группировать массив объектов в определенный формат

1

У меня есть массив объектов в этом формате:

const arr = [
    {
        parentKey: {
            myKey1: 'someStringA',
            myKey2: 'anotherStringA',
            myKey3: false,
            myKey4: true
        },
        anotherKey: {}
    },
    {
        parentKey: {
            myKey1: 'someStringA',
            myKey2: 'anotherStringA',
            myKey3: true,
            myKey4: false
        },
        anotherKey: {}
    },
    {
        parentKey: {
            myKey1: 'someStringA',
            myKey2: 'anotherStringA',
            myKey3: true,
            myKey4: false
        },
        anotherKey: {}
    },
    {
        parentKey: {
            myKey1: 'someStringA',
            myKey2: 'anotherStringA',
            myKey3: true,
            myKey4: true
        },
        anotherKey: {}
    },
    {
        parentKey: {
            myKey1: 'someStringA',
            myKey2: 'anotherStringB',
            myKey3: true,
            myKey4: true
        },
        anotherKey: {}
    },
    {
        parentKey: {
            myKey1: 'someStringB',
            myKey2: 'anotherStringB',
            myKey3: false,
            myKey4: true
        },
        anotherKey: {}
    }
];

И мне нужно получить результат в этом формате:

const result = [
    {
        props: {
            myKey1: 'someStringA',
            myKey2: 'anotherStringA',
            myKey3: false,
            myKey4: true
        },
        entries: [
            {
                parentKey: {
                myKey1: 'someStringA',
                myKey2: 'anotherStringA',
                myKey3: false,
                myKey4: true
                },
                anotherKey: {}
            }
        ] 
    },
    {
        props: {
            myKey1: 'someStringA',
            myKey2: 'anotherStringA',
            myKey3: true,
            myKey4: false
        },
        entries: [
            {
                parentKey: {
                myKey1: 'someStringA',
                myKey2: 'anotherStringA',
                myKey3: true,
                myKey4: false
                },
                anotherKey: {}
            },
            {
                parentKey: {
                    myKey1: 'someStringA',
                    myKey2: 'anotherStringA',
                    myKey3: true,
                    myKey4: false
                },
                anotherKey: {}
            }
        ] 
    },
    {
        props: {
            myKey1: 'someStringA',
            myKey2: 'anotherStringA',
            myKey3: true,
            myKey4: true
        },
        entries: [
            {
                parentKey: {
                    myKey1: 'someStringA',
                    myKey2: 'anotherStringA',
                    myKey3: true,
                    myKey4: true
                },
                anotherKey: {}
            }
        ] 
    },
    {
        props: {
            myKey1: 'someStringA',
            myKey2: 'anotherStringB',
            myKey3: true,
            myKey4: true
        },
        entries: [
            {
                parentKey: {
                    myKey1: 'someStringA',
                    myKey2: 'anotherStringB',
                    myKey3: true,
                    myKey4: true
                },
                anotherKey: {}
            }
        ] 
    },
    {
        props: {
            myKey1: 'someStringB',
            myKey2: 'anotherStringB',
            myKey3: false,
            myKey4: true
        },
        entries: [
            {
                parentKey: {
                    myKey1: 'someStringB',
                    myKey2: 'anotherStringB',
                    myKey3: false,
                    myKey4: true
                },
                anotherKey: {}
            }
        ] 
    }
];

Я пытаюсь написать функцию groupArray, которая будет группировать массив объекта на основе массива предоставленных ключей, например groupArray(arr, ['parentKey.myKey1', 'parentKey.myKey2', 'parentKey.myKey3', 'parentKey.myKey4']) но не удалось. Вот jsfiddle с моим кодом. Все записи в настоящее время помещаются в результирующий массив без группировки.

Не могли бы вы дать мне подсказку, как исправить мою функцию.

  • 0
    Привет не уверен, что вы имеете в виду, вы пытаетесь сгруппировать объекты вместе? Предоставленный формат результата просто реструктурирует исходный список без группировки
  • 0
    Записи сгруппированы по предоставленным ключам. Если вы проверите результат, вы увидите, что второй объект result включает в себя 2 объекта из исходного массива arr . Я пытаюсь заархивировать что-то похожее на пакет группового массива , но без вложенности.
Теги:
object
arrays
grouping

1 ответ

1
Лучший ответ

Вы можете использовать хеш-таблицу для группировки одной и той же группы и функцию для получения значения из объекта с помощью этого пути через вложенные свойства.

function groupArray(array, keys) {
    function getValue(object, path) {
        return path.split('.').reduce((o, k) => (o || {})[k], object);
    }

    var hash = Object.create(null),
        result = [];

    array.forEach(function (o) {
        var key = keys.map(k => getValue(o, k)).join('|');
        if (!hash[key]) {
            hash[key] = { props: Object.assign(...keys.map(k => ({ [k.split('.').pop()]: getValue(o, k) }))), entries: [] };
            result.push(hash[key])
        }
        hash[key].entries.push(o);
    });
    return result;
}

var array = [{ parentKey: { myKey1: 'someStringA', myKey2: 'anotherStringA', myKey3: false, myKey4: true }, anotherKey: {} }, { parentKey: { myKey1: 'someStringA', myKey2: 'anotherStringA', myKey3: true, myKey4: false }, anotherKey: {} }, { parentKey: { myKey1: 'someStringA', myKey2: 'anotherStringA', myKey3: true, myKey4: false }, anotherKey: {} }, { parentKey: { myKey1: 'someStringA', myKey2: 'anotherStringA', myKey3: true, myKey4: true }, anotherKey: {} }, { parentKey: { myKey1: 'someStringA', myKey2: 'anotherStringB', myKey3: true, myKey4: true }, anotherKey: {} }, { parentKey: { myKey1: 'someStringB', myKey2: 'anotherStringB', myKey3: false, myKey4: true }, anotherKey: {} }],
    result = groupArray(array, ['parentKey.myKey1', 'parentKey.myKey2', 'parentKey.myKey3', 'parentKey.myKey4']);

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню