0

My JSON looks like this

{"rows":[
    {"shiftId":1,"shift":"Morning","item":"Tea","value":20},
    {"shiftId":1,"shift":"Morning","item":"Coffee","value":30},
    {"shiftId":2,"shift":"Evening","item":"Tea","value":40},
    {"shiftId":2,"shift":"Evening","item":"Coffee","value":35}
]}

and I am looking to merge all the same shift and add the values of the merged keys together and create new Object for item to get something looking like this

{"rows":[
    {
     "shiftId":1,
     "shift":"Morning",
     "item":[{"itemName":"Tea"},{"itemName":"Coffee"}],
     "value":50
     },
    {
    "shiftId":2,
    "shift":"Evening",
    "item":[{"itemName":"Tea"},{"itemName":"Coffee"}],
    "value":75
    }
]}

I am try like this

    var merged = {rows: []};
                data.forEach(function (source) {
                    if (!merged.rows.some(function (row) {
                            return row.shiftId == source.shiftId;
                        })) {
                        merged.rows.push({
                            shiftId: source.shift,
                            shift: source.shift,
                            item: [{
                                itemName: source.shift
                            }],
                            value: source.value
                        });
                    } else {
                        var existRow = merged.rows.filter(function (existRow) {
                            return existRow.shiftId == source.shiftId
                        })[0];
                        existRow.total += source.total;
                        existRow.item = source.item.push(existRow.item);
                    }
                });

But not working correctly. Thanks advance.

6
  • 5
    What did you attempt so far? What is the code you made so far to try this? Commented Jun 26, 2017 at 11:06
  • I would recommend reading about Array.prototype.reduce. Commented Jun 26, 2017 at 11:09
  • I am trying. thanks for fast reply @selten98 Commented Jun 26, 2017 at 11:12
  • Thanks @evolutionxbox Commented Jun 26, 2017 at 11:12
  • 1
    "Can anyone help me" ... need to help yourself first by showing what you have tried. Stackoverflow is not a free code writing service. The objective here is to help you fix your code Commented Jun 26, 2017 at 11:17

4 Answers 4

3

You could use a hash table as a reference to the objects with the same shiftId and return a new array with the collected and grouped data.

var data = { rows: [{ shiftId: 1, shift: "Morning", item: "Tea", value: 20 }, { shiftId: 1, shift: "Morning", item: "Coffee", value: 30 }, { shiftId: 2, shift: "Evening", item: "Tea", value: 40 }, { shiftId: 2, shift: "Evening", item: "Coffee", value: 35 }] },
    result = {
        rows: data.rows.reduce(function (hash) {
            return function (r, a) {
                if (!hash[a.shiftId]) {
                    hash[a.shiftId] = { shiftId: a.shiftId, shift: a.shift, item: [], value: 0 };
                    r.push(hash[a.shiftId]);
                }
                hash[a.shiftId].item.push({ itemName: a.item });
                hash[a.shiftId].value += a.value;
                return r;
            };
        }(Object.create(null)), [])
    };

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

Sign up to request clarification or add additional context in comments.

2 Comments

Why use (Object.create(null)) and not ({})? Is it to guarantee no inherited properties?
@evolutionxbox, because if you have an id like toString, then it is already in the object, because of the prototype. Object.create(null) generates an object without prototypes. it is a really empty opbject.
0

Use a hash table:

var hash={};
var input={"rows":[
{"shiftId":1,"shift":"Morning","item":"Tea","value":20},
{"shiftId":1,"shift":"Morning","item":"Coffee","value":30},
{"shiftId":2,"shift":"Evening","item":"Tea","value":40},
{"shiftId":2,"shift":"Evening","item":"Coffee","value":35}
]}.rows;

input.forEach(function(row){
  var el=(hash[row.shiftId]=hash[rows.shiftId]||{shiftId:row.shiftId,shift:row.shift,items:[],value:0});
   el.items.push({itemName:row.itemName});
   el.value+=row.value;
});

Now you can create your result like this:

var result={rows:[]};
for(key in hash){
 result.rows.push(hash[key]);
}

Comments

0

Using Array.prototype.reduce()

const arr = [{
        "shiftId": 1,
        "shift": "Morning",
        "item": "Tea",
        "value": 20
    },
    {
        "shiftId": 1,
        "shift": "Morning",
        "item": "Coffee",
        "value": 30
    },
    {
        "shiftId": 2,
        "shift": "Evening",
        "item": "Tea",
        "value": 40
    },
    {
        "shiftId": 2,
        "shift": "Evening",
        "item": "Coffee",
        "value": 35
    }
];

const newArr = arr.reduce((acc, item, i) => {
    if (!acc.length) { // First time
        acc.push(item)
        return acc;
    }
    if (acc[acc.length - 1].shiftId === item.shiftId) { // if current shiftId === last shiftId
        if (!(acc[acc.length - 1].item instanceof Array)) {
            acc[acc.length - 1].item = [{ // Convert item to be an array
                "itemName": acc[acc.length - 1].item
            }]
        }
        acc[acc.length - 1].item.push({ // Add current item name to the last item array
            "itemName": item.item
        });
        acc[acc.length - 1].value = acc[acc.length - 1].value + item.value // value addition
    } else { // If new shiftId
        acc.push(item);
    }
    return acc;
}, []);

console.log(newArr);

Comments

0
a = {"rows":[
    {"shiftId":1,"shift":"Morning","item":"Tea","value":20},
    {"shiftId":1,"shift":"Morning","item":"Coffee","value":30},
    {"shiftId":2,"shift":"Evening","item":"Tea","value":40},
    {"shiftId":2,"shift":"Evening","item":"Coffee","value":35}
]};
newa = {"rows":[]};

lastshiftid = -1;
newkey = -1;
for(key in a.rows){
  curshiftid = a.rows[key].shiftId;

  o = {"item":a.rows[key].item};
  if(lastshiftid!=curshiftid){
    newkey++;
    a.rows[key].item = [];
    newa.rows.push(a.rows[key]);    
  }

  newa.rows[newkey].item.push(o);

  lastshiftid = curshiftid;
}
console.log(newa.rows);

Fiddle: https://jsfiddle.net/t74ygy9L/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.