Skip to content
Advertisement

Looping array to re-format data structure

I want to reformat an array but result is not correct. Please check my code first.

var items = [
              {
                room_type : 'Room A',
                product_type : 'Product Type X',
                formula : '10',
              },
              {
                room_type : 'Room A',
                product_type : 'Product Type Y',
                formula : '20',
              },
                {
                room_type : 'Room B',
                product_type : 'Product Type Z',
                formula : '30',
              },             

];

var new_items = [];
var obj = [];

 $.each(items, function (i, data) {
    var room_type = data.room_type;
    var product_type = data.product_type;
    var formula = data.formula;
    
    obj[product_type] = [];
    obj[product_type]['formula'] = formula;   
    new_items[room_type] = obj;

});

console.log(new_items);

From my example There are duplicate Room Type A I want to re-format like

var new_items = [
                  'Room A' : {
                    'Product Type X' : {formula : '10'},      
                    'Product Type Y' : {formula : '20'}                       
                  },
                  'Room B' : {
                    'Product Type Z' : {formula : '30'}
                  }
                ];

but result of my code is duplicate. Thank you for help.

Advertisement

Answer

You need an object as result and add the properties from the object.

var items = [{ room_type: 'Room A', product_type: 'Product Type X', formula: '10' }, { room_type: 'Room A', product_type: 'Product Type Y', formula: '20' }, { room_type: 'Room B', product_type: 'Product Type Z', formula: '30' }],
    result = items.reduce((r, o) => {
        ['room_type', 'product_type']
            .reduce((q, k) => q[o[k]] = q[o[k]] || {}, r)
            .formula = o.formula;
        return r;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement