0

I have parsed a csv file which gives me an array like this:

[{
"year": 2019,
"month": 6,
"day": 25,
"hour": 4,
"minute": 0,
"temperature": 26.52
},
{
"year": 2019,
"month": 6,
"day": 25,
"hour": 4,
"minute": 0,
"temperature": 26.52
}]

I want to merge minute,hour,day,month,year to a single key. Like this:

"time": "2019-07-02 09:57:35"

so i can use this as a datetime object on my API.

The way I am currently getting data is:

 const cleanKeys = [
 'year',
 'month',
 'day',
 'hour',
 'minute',
 'temperature',
 ];
 const dataAsObject = totalData.map(function (values) {
 return cleanKeys.reduce(function (o, k, i) {
 o[k] = values[i];
 return o;
 }, {})
 });

This is basically adding a header key to all data. I am only interested in merging minute, hour, day, month, year column.

asked Jul 2, 2019 at 6:49
3
  • 2
    OK...what's stopping you from just doing year + "-" + month, etc? Commented Jul 2, 2019 at 6:52
  • 2
    That wouldn't be an array - we call them objects in JavaScript Commented Jul 2, 2019 at 6:58
  • Is there any way I can do this inside of loop? Commented Jul 2, 2019 at 9:46

2 Answers 2

1

I suggest you to use built in Date constructor:

var obj = {"year": 2019,
"month": 6,
"day": 25,
"hour": 4,
"minute": 0,
"temperature": 26.52};
const date = new Date(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute);
const newObj = {date, temperature: obj.temperature};
console.log(JSON.stringify(newObj));

EDIT:

please find below updated answer using date in loop:

const arr = [{
"year": 2019,
"month": 6,
"day": 25,
"hour": 4,
"minute": 0,
"temperature": 26.52
},
{
"year": 2019,
"month": 6,
"day": 25,
"hour": 4,
"minute": 0,
"temperature": 26.52
}];
const newArr = arr.reduce((a,c) => {
	const date = new Date(c.year, c.month - 1, c.day, c.hour, c.minute);
	a.push({date, temperature: c.temperature});
	return a;
}, []);
console.log(JSON.stringify(newArr));

answered Jul 2, 2019 at 6:56
Sign up to request clarification or add additional context in comments.

1 Comment

How can I do this inside of loop? If you look closely to how I am getting the data you may understand
0

You can create the string yourself, e.g.:

yourArray["time"] = `${yourArray.year}-${yourArray.month}-${yourArray.day} ${yourArray.hours}:${yourArray.minutes}:${yourArray.seconds}`;
answered Jul 2, 2019 at 6:57

1 Comment

Nice, but can I use this on reduce method?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.