Search code examples
javascriptreactjsarraysloopsobject

convert a property and return the array of object using javascript


I have array of object, in which property time

is in format dddd hh:min and need to convert to minutes, return the array object.

Current format dddd: days(in 4 digits) hh: hour(in 2 digits) min: (2 digits)

I tried below code , works but return array of object is wrong.

So, I need to know how to convert the time property to minutes, and return the

arrayobject using javascript. Better approach also can

var arrobj=[
  {id:1, time: '0001 03:40'},
  {id:2, time: '0016 10:20'},
  {id:3, time: '1014 12:04'},
  {id:4, time: '0412 01:01'},
]

function convertToMinutes(value) {
  var splitTime = value.split(' ');
  var dayToMinutes = splitTime[0] * 1440;
  console.log(dayToMinutes);
  var splitHrMin = splitTime[1].split(':');
  console.log(splitHrMin);
  var splitHr = splitHrMin[0] * 60;
  console.log(splitHr);
  var splitMin = splitHrMin[1];
  var timeInMinutes = dayToMinutes + splitHr + splitMin;
  console.log(timeInMinutes);
  return timeInMinutes;
}

for(let item of arrobj) {
  var result = this.convertToMinutes(item.time);
  console.log(result);
}

Expected Output

[
  {id:1, time: '1660'},
  {id:2, time: '23660'},
  {id:3, time: '1460884'},
  {id:4, time: '593341'},
]


Solution

  • This should work for what you are trying to achieve

    var arrobj=[
      {id:1, time: '0001 03:40'},
      {id:2, time: '0016 10:20'},
      {id:3, time: '1014 12:04'},
      {id:4, time: '0412 01:01'},
    ]
    
    const convertToMinutes = (obj) => {
    const newObj = [];
    obj.forEach(val => {
    var day = val.time.split(" ");
    var [hr, min] = day[1].split(":");
     var time = (((+day[0] * 24) + +hr) * 60) + +min;
     newObj.push({id: val.id, time: `${time}`})
    });
     return newObj;
    };
    
    console.log(convertToMinutes(arrobj));