1

During work I have problem with this task, here is my data :

var order = [
      {area: "RFCC",ru: "R401",tot: 3,unit: "OFFSITE"},
      {area: "RFCC",ru: "R401",tot: 1,unit: "RCU"}];

I want the result should be like this :

var order = [
    {area:["RFCC","RFCC"],ru:["R401","R401"],tot:[4],unit:["OFFSITE","RCU"]}]

Anyone know solution for this? Thanks in advance.

  • 5
    Why would you need final result to be an array with only one object in it rather than just a single object and no array? – charlietfl Nov 12 '18 at 04:09
  • https://stackoverflow.com/questions/18498801/how-to-merge-two-object-values-by-keys https://stackoverflow.com/questions/53224923/merge-array-of-objects-by-object-key – Matt Nov 12 '18 at 04:16
  • @charlietfl because I want to display data chart with single object – Hamzah Aznageel Nov 12 '18 at 04:38

2 Answers2

1

You could use Array#reduce() to achieve this, by the following:

var order = [
      {area: "RFCC",ru: "R401",tot: 3,unit: "OFFSITE"},
      {area: "RFCC",ru: "R401",tot: 1,unit: "RCU"}
];

var result = order.reduce((result, item) => {
  
  const { area, ru, tot, unit } = result[0]
   
  area.push( item.area );
  ru.push( item.ru );
  unit.push( item.unit );
  tot[0] = parseInt(tot[0]) + parseInt(item.tot);
  
  return result

}, [{ area : [], ru : [], tot: [ 0 ], unit : [] }])

console.log(result);
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
1

You can use "for..of" to loop through the array objects

var order = [
      {area: "RFCC",ru: "R401",tot: 3,unit: "OFFSITE"},
      {area: "RFCC",ru: "R401",tot: 1,unit: "RCU"}
];
  
var result = {}

for(let obj of order) {
  for(let [key, value] of Object.entries(obj)) {
    
    typeof value == "string" && (
      result[key] = result[key] ? result[key].concat(value) : [value]
    )
    
    typeof value == "number" && (
      result[key] = result[key] ? [result[key][0] + value] : [value]
    )
  }
}

console.log(result)
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22
  • 1
    You’re Welcome!! As these two answers follow different approach. Pls do spend some time understanding both of these as this will help you in future problems. Also in case of any issue do let us know. – Nitish Narang Nov 12 '18 at 04:55