Как оптимизировать преобразование данных в javascript?
Все привет.
У меня есть исходный массив: const array = [ {name: 'prop1', title: 'title1'}, {name: 'prop2', title: 'title2'}, {name: 'prop3', title: 'title3'}, {name: 'prop1', title: 'title4'}, {name: 'prop1', title: 'title5'}, ] Результат, который необходимо получить: [ { prop1: [ {name: "prop1", title: "title1"}, {name: "prop1", title: "title4"}, {name: "prop1", title: "title5"} ] }, { prop2: [ {name: "prop2", title: "title2"} ], }, { prop3: [ {name: "prop3", title: "title3"} ] } ] Моё решение: function f(array) { const object = array.reduce((accumulator, currentValue) => { if (!accumulator[currentValue.name]) { accumulator[currentValue.name] = []; } accumulator[currentValue.name].push(currentValue); return accumulator; }, {}); console.log('object', object); return Object.keys(object).reduce((accumulator, currentValue) => { accumulator.push({ [currentValue]: object[currentValue] }); return accumulator; }, []); } Подскажите, как оптимизировать данное решение? Пока, что, кажется, что можно сделать это преобразование, используя один цикл. |
dc65k,
<script> const array = [ {name: 'prop1', title: 'title1'}, {name: 'prop2', title: 'title2'}, {name: 'prop3', title: 'title3'}, {name: 'prop1', title: 'title4'}, {name: 'prop1', title: 'title5'}, ]; const f = a => a.reduce((a, b) => { let {name} = b; if (!a[name]) a.accumulator.push({[name]: a[name] = []}); a[name].push(b); return a; }, {accumulator: []}).accumulator; let a = f(array); document.write(`<pre>${JSON.stringify(a, "", 1)}</pre>`) </script> |
Спасибо.
|
Часовой пояс GMT +3, время: 17:53. |