Home > database >  how merge arrays of objects by specific common property in on array of objects javascript
how merge arrays of objects by specific common property in on array of objects javascript

Time:08-29

I want merge bellow arrays based on hour property and result should be a array of objects

 let sale = [
        {hour: '00', sale: 1514},
        {hour: '01', sale: 1038},
        {hour: '02', sale: 646},
        {hour: '03', sale: 344}
    ]
    let charge = [
        {hour: '00', charge: 1514},
        {hour: '01', charge: 1038},
        {hour: '02', charge: 646},
        {hour: '03', charge: 344}
    ]
    let errors = [
        {hour: '00', errors: 1514},
        {hour: '01', errors: 1038},
        {hour: '02', errors: 646},
        {hour: '03', errors: 344}
    ]

and convert to

  let all = [
        {hour: '01', sale: 1514, errors: 1038, charge: 646},
        {hour: '02', sale: 1514, errors: 646, charge: 646},
        {hour: '03', sale: 1514, errors: 344, charge: 646}
    ]

CodePudding user response:

You could use an object for grouping the hours and get the values from the object as result.

const
    sale = [{ hour: '00', sale: 1514 }, { hour: '01', sale: 1038 }, { hour: '02', sale: 646 }, { hour: '03', sale: 344 }],
    charge = [{ hour: '00', charge: 1514 }, { hour: '01', charge: 1038 }, { hour: '02', charge: 646 }, { hour: '03', charge: 344 }],
    errors = [{ hour: '00', errors: 1514 }, { hour: '01', errors: 1038 }, { hour: '02', errors: 646 }, { hour: '03', errors: 344 }],
    result = Object.values([...sale, ...charge, ...errors].reduce((r, o) => {
        r[o.hour] = { ...r[o.hour], ...o };
        return r;
    }, {}));

console.log(result);

CodePudding user response:

I decided share my experience - I solved it by the code below

let sale = [
  {hour: '00', sale: 1514},
  {hour: '01', sale: 1038},
  {hour: '02', sale: 646},
  {hour: '03', sale: 344}
];
let charge = [
  {hour: '00', charge: 1514},
  {hour: '01', charge: 1038},
  {hour: '02', charge: 646},
  {hour: '03', charge: 344}
];
let errors = [
  {hour: '00', errors: 1514},
  {hour: '01', errors: 1038},
  {hour: '02', errors: 646},
  {hour: '03', errors: 344}
];

let merge = [...sale, ...charge, ...errors]
let obj = []
for (let i = 0; i < 4; i  ) {
  let obj2 = {}
  for (let x of merge) {
    if (parseInt(x.hour) === i) {
      Object.assign(obj2, x);
    }
  }
  if (obj2) obj.push(obj2)
}
console.log(obj)

  • Related