Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda