Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

179
Vistas
How to merge two objects with same property in Node JS

I have a JSON Data like this:

"Data": [
            {
                "time": "18:40:43",
                "count": 7,
                "endTime": "15:46:25",
                "date": "2019-01-16",
                "dow": "Thursday"
            },
            {
                "count": 11,
                "time": "16:39:52",
                "endTime": "19:41:03",
                "dow": "Thursday",
                "date": "2019-01-16"
            },
]

I want to merge two objects in this array, but it have same properties like date, dow

at the end I want to represent data like this:

"Data": [
            {
                "time": "16:39:52",
                "count": 18,
                "date": "2019-01-16",
                "dow": "Thursday"
                "endTime": "19:41:03",
            },
]

time: should be least from both objects and endTime should be largest of both of them count should be sum of both. date and dow is common in both objects

How can I merge these object in this way in node JS?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

const data=[
            {
                "time": "18:40:43",
                "count": 7,
                "endTime": "15:46:25",
                "date": "2019-01-16",
                "dow": "Thursday"
            },
            {
                "count": 11,
                "time": "16:39:52",
                "endTime": "19:41:03",
                "dow": "Thursday",
                "date": "2019-01-16"
            },
];
let date=(time)=>new Date().setHours(...time.split(":"));

let newData=[];
data.forEach((item)=>{
  let findItem=newData.findIndex((e)=>e.date===item.date && e.dow===item.dow);
  if(findItem!=-1){
  let find=data.filter((e)=>e.dow===item.dow && e.date===item.date);
  let time=find.filter((i)=>find.find(i2=>date(i2.time)>date(i.time)));
    let endTime=find.filter((i)=>find.find(i2=>date(i2.endTime)<date(i.endTime)));
  item.endTime=endTime?.[0]?.endTime || item?.endTime;
  item.time=time?.[0]?.time || item?.time;
  item.count=find.map((e)=>e.count).reduce((partialSum, a) => partialSum + a, 0);
   let findItem=newData.findIndex((e)=>e.date===item.date && e.dow===item.dow);
   if(findItem!=-1) newData.splice(findItem,1);
   newData.push(item);
  }

 else newData.push(item);
});
console.log(newData);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here's a simple and readable answer:

const data = [
  {
    time: "18:40:43",
    count: 7,
    endTime: "15:46:25",
    date: "2019-01-16",
    dow: "Thursday",
  },
  {
    count: 11,
    time: "16:39:52",
    endTime: "19:41:03",
    dow: "Thursday",
    date: "2019-01-16",
  },
];
const mergeObjects = (data) => {
  mergedObj = { ...data[0] };
  for (i = 1; i < data.length; i++) {
    const obj = data[i];
    for (const key in obj) {
      switch (key) {
        case "count":
          mergedObj.count = (mergedObj.count || 0) + obj.count;
        case "time":
          mergedObj.time =
            mergedObj.time < obj.time ? mergeObjects.time : obj.time;
        case "endTime":
          mergedObj.endTime = mergedObj.endTime > obj.endTime ? mergeObjects.endTime : obj.endTime;
      }
    }
  }
  return mergedObj;
};

console.log(mergeObjects(data));

output

{
    "time": "16:39:52",
    "count": 18,
    "date": "2019-01-16",
    "dow": "Thursday"
    "endTime": "19:41:03",
},
about 4 years ago · Juan Pablo Isaza Denunciar

0

Assuming

  • "Data" would have only two objects inside it
  • time would be in "HH::MM::SS" format

Pass the values onto constructJSON utility function which would return the formatted value

var Data = [
            {
                "time": "18:40:43",
                "count": 7,
                "endTime": "15:46:25",
                "date": "2019-01-16",
                "dow": "Thursday"
            },
            {
                "count": 11,
                "time": "16:39:52",
                "endTime": "19:41:03",
                "dow": "Thursday",
                "date": "2019-01-16"
            },
]


function constructJSON(data)
{
 const returnData = {}
 returnData['count'] = data[0].count + data[1].count
 returnData['date'] = data[0].date    // since its common for both
 returnData['dow'] = data[0].dow      // since its common for both
 returnData['time'] = parseInt(data[0].time.split(':').join(''),10) < parseInt(data[1].time.split(':').join(''),10) ? data[0].time:data[1].time;
  returnData['endTime'] = parseInt(data[0].endTime.split(':').join(''),10) > parseInt(data[1].endTime.split(':').join(''),10) ? data[0].endTime:data[1].endTime;
 
  return returnData
}

console.log(constructJSON(Data))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda