This is the code to form a JSON that a server expects. But there are some problems though
<!DOCTYPE html>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//var acc = {};
var x = 10;
var y = 20;
var z = 30;
var output = [];
output[0] = {
name: "Accelerometer_X",
value: JSON.parse(x), // retrieve x
};
output[1] = {
name: "Accelerometer_Y",
value: JSON.parse(y), // retrieve y
};
output[2] = {
name: "Accelerometer_Z",
value: JSON.parse(z) // retrieve z
};
var record = [];
record[0] = {
starttime: new Date(),
output: output,
};
var observations = [];
observations[0] = {
sensor: "",
record: record,
};
var fromData = {};
fromData.version = "1.0.1";
fromData.observations = observations;
alert(JSON.stringify(fromData));
console.log(JSON.stringify(fromData));
//-->
</script>
</body>
</html>
The output JSON is:
{
"version": "1.0.1",
"observations": [
{
"sensor": "",
"record": [
{
"starttime": "2014-08-15T16:01:34.711Z",
"output": [
{
"name": "Accelerometer_X",
"value": 10
},
{
"name": "Accelerometer_Y",
"value": 20
},
{
"name": "Accelerometer_Z",
"value": 30
}
]
}
]
}
]
}
But the expected JSON is:
{
"version": "1.0.1",
"observations": [
{
"sensor": "",
"record": [
{
"starttime": "1-JAN-2014 15:30:00 IST",
"output": [
{
"name": "Accelerometer_X",
"value": "10"
},
{
"name": "Accelerometer_Y",
"value": "20"
},
{
"name": "Accelerometer_Z",
"value": "30"
}
]
}
]
}
]
}
The values in expected JSON is within "" ie.
{
"name": "Accelerometer_Z",
"value": "30"
}
But the produced JSON is :
{
"name": "Accelerometer_Z",
"value": 30
}
And there is another problem that is the starttime. The expected starttime format is
1-JAN-2014 15:30:00 IST
The produced starttime is:
2014-08-15T16:01:34.711Z
I do not know how to change this. Please help me out.
You shouldn't use JSON.parse on the values that you want to put in the object. The JSON.parse method is used to parse a JSON string into an object, but the values are not JSON strings.
Remove the JSON.parse call (as it doesn't change the value), and use the toString method to turn the values into strings:
output[0] = {
name: "Accelerometer_X",
value: x.toString(),
};
output[1] = {
name: "Accelerometer_Y",
value: y.toString(),
};
output[2] = {
name: "Accelerometer_Z",
value: z.toString()
};
There is no build in function that formats the date that way, you would need to make your own. Something like:
function formatDate(d) {
return d.getDate() + '-' + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + " IST";
}
Usage:
record[0] = {
starttime: formatDate(new Date()),
output: output,
};
This is the code so far working:
<!DOCTYPE html>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//var acc = {};
var x = 10;
var y = 20;
var z = 30;
//var accString = JSON.stringify(acc); // that's what you have
var output = [];
output[0] = {
name: "Accelerometer_X",
value: x.toString(), // retrieve x
};
output[1] = {
name: "Accelerometer_Y",
value: y.toString(), // retrieve y
};
output[2] = {
name: "Accelerometer_Z",
value: z.toString() // retrieve z
};
var record = [];
record[0] = {
starttime: new Date(),
output: output,
};
var observations = [];
observations[0] = {
sensor: "",
record: record,
};
var fromData = {};
fromData.version = "1.0.1";
fromData.observations = observations;
alert(JSON.stringify(fromData));
console.log(JSON.stringify(fromData));
//-->
</script>
</body>
</html>
But the time is having problem still now. Anyone to resolve this issue?
Related
As said above, I don't know how to use this kind of JSON response from my server-side php which I got by using this code echo json_encode(array_merge($outp, $outp2));
[
{
"stuid":"12",
"stuname":"Velino Meratis",
"stucourse":"BSIT",
"stustat":"0",
"stulyear":"4",
"stulog":"feb 16 2017"
},
{
"stuid":"13",
"stuname":"Alana Melker",
"stucourse":"BSCE",
"stustat":"1",
"stulyear":"5",
"stulog":"feb 16 2017"
},
{
"stuid":"12",
"cname":"InfoTech000",
"clog":"1"
},
{
"stuid":"12",
"cname":"InfoTech001",
"clog":"2"
},
{
"stuid":"12",
"cname":"C101",
"clog":"3"
},
{
"stuid":"13",
"cname":"CE000",
"clog":"4"
},
{
"stuid":"13",
"cname":"CE001",
"clog":"5"
},
{
"stuid":"13",
"cname":"C101",
"clog":"6"
}
]
If I use this code in my client side javascript
if (this.readyState == 4 && this.status == 200) {
students = JSON.parse(this.responseText);
students.forEach(function(item){
console.log(item.stuid);
x = item.stuid;
document.getElementById("demo").innerHTML += x + " " + item.stuname + "<br>" + item.cname + "<br>";
});
}
it just ends up giving me this:-
12 Velino Meratis
undefined
13 Alana Melker
undefined
Somehow I can iterate the stuid and the stunamebut it won't allow them to contain the cname as an array with them.
How can I turn that into something like this:-
12 Velino Meratis
InfoTech000, InfoTech001, C101
13 Alana Melker
CE000, CE001, C101
Can someone Help and Elaborate on this?
You can check if the array contains the key or not, that way you will be saved from "undefined" error.
You can do it this way
if(item.hasOwnProperty('cname'))
{
console.log(item.cname);
}
You can use this for stuname or other keys also.
You need to merge student objects in your array by unique IDs. One way to do this is to add new stuids to an array and merge it with subsequent items with same stuid. Once you have array of unique students, you can proceed with other goals.
if (this.readyState == 4 && this.status == 200) {
var students_raw = JSON.parse(this.responseText);
var students = [];
students_raw.forEach(function(item){
var existing = students.find($item => item.stuid === $item.stuid);
if (existing) {
existing = Object.assign({}, existing, item);
} else {
students.push(item);
}
});
// your print loop
students.forEach(function(item) {
var x = item.stuid;
document.getElementById("demo").innerHTML += x + " " + item.stuname + "<br>" + item.cname + "<br>";
});
}
Please note: Array.reduce() and Object.assign() are not supported widely. you may need to polyfill these methods
NOTE: This answer assumes you're willing and able to change the data coming from PHP
Credit where credit is due, this is an extension of #Magnus Eriksson's comment.
It would be preferable to keep the relevant data associated with each other. You should get better flexibility with well-formed data. Ideally, you should do this server side and present the data to the client already well formatted.
You should try and achieve something similar to the following for your output:
[{
"stuid": "12",
"stuname": "Velino Meratis",
"stucourse": "BSIT",
"stustat": "0",
"stulyear": "4",
"stulog": "feb 16 2017",
"classes": [{
"cname": "InfoTech000",
"clog": "1"
}, {
"cname": "InfoTech001",
"clog": "2"
}, {
"cname": "C101",
"clog": "3"
}]
}, {
"stuid": "13",
"stuname": "Alana Melker",
"stucourse": "BSCE",
"stustat": "1",
"stulyear": "5",
"stulog": "feb 16 2017",
"classes": [{
"cname": "CE000",
"clog": "4"
}, {
"cname": "CE001",
"clog": "5"
}, {
"cname": "C101",
"clog": "6"
}]
}];
Note I've used classes as the property name as it appears we are working with Courses and their classes.
Your javascript will now look like:
if (this.readyState == 4 && this.status == 200) {
students = JSON.parse(this.responseText);
students.forEach(function(item){
console.log(item.stuid);
x = item.stuid;
document.getElementById("demo").innerHTML += x + " " + item.stuname + "<br>" + item.classes.map(function(elem){
return elem.cname;}).join(",") + "<br>";
});
}
Note the map function won't work in IE8 and lower.
Now for a working example:
var students = [{
"stuid": "12",
"stuname": "Velino Meratis",
"stucourse": "BSIT",
"stustat": "0",
"stulyear": "4",
"stulog": "feb 16 2017",
"classes": [{
"cname": "InfoTech000",
"clog": "1"
}, {
"cname": "InfoTech001",
"clog": "2"
}, {
"cname": "C101",
"clog": "3"
}]
}, {
"stuid": "13",
"stuname": "Alana Melker",
"stucourse": "BSCE",
"stustat": "1",
"stulyear": "5",
"stulog": "feb 16 2017",
"classes": [{
"cname": "CE000",
"clog": "4"
}, {
"cname": "CE001",
"clog": "5"
}, {
"cname": "C101",
"clog": "6"
}]
}];
students.forEach(function(item){
console.log(item.stuid);
x = item.stuid;
document.getElementById("demo").innerHTML += x + " " + item.stuname + "<br>" + item.classes.map(function(elem){
return elem.cname;}).join(",") + "<br>";
});
<div id="demo"></div>
As mentioned in other answers and comments, the issue with your existing code, is not all objects in your json array have the property you're referencing.
You can try like this once also
HTML
<div id="result"></div>
SCRIPT
var dataJSON = [
{
"stuid":"12",
"stuname":"Velino Meratis",
"stucourse":"BSIT",
"stustat":"0",
"stulyear":"4",
"stulog":"feb 16 2017"
},
{
"stuid":"13",
"stuname":"Alana Melker",
"stucourse":"BSCE",
"stustat":"1",
"stulyear":"5",
"stulog":"feb 16 2017"
},
{
"stuid":"12",
"cname":"InfoTech000",
"clog":"1"
},
{
"stuid":"12",
"cname":"InfoTech001",
"clog":"2"
},
{
"stuid":"12",
"cname":"C101",
"clog":"3"
},
{
"stuid":"13",
"cname":"CE000",
"clog":"4"
},
{
"stuid":"13",
"cname":"CE001",
"clog":"5"
},
{
"stuid":"13",
"cname":"C101",
"clog":"6"
}
] ;
var arr = {};
for(var i = 0 ; i< dataJSON.length ; i++){
var ele = dataJSON[i];
if(arr[ ele.stuid ]==undefined){
arr[ ele.stuid ] = {};
}
arr[ ele.stuid ]['stuid'] = ele.stuid;
if(ele.stuname!=undefined){
arr[ ele.stuid ]['stuname'] = ele.stuname;
}
if(arr[ ele.stuid ]['cname'] == undefined){
arr[ ele.stuid ]['cname'] = [];
}
if(ele.cname!=undefined){
arr[ ele.stuid ]['cname'].push(ele.cname);
}
}
var str = '';
for(var key in arr){
var obj = arr[key];
str += obj['stuid'] +" "+obj['stuname']+'<br/>';
str += obj['cname'].toString()+'<br/>';
}
document.getElementById("result").innerHTML = str;
Thanks,
How do I push an object into an specified array that only updates that array? My code pushes an object and updates all arrays, not just the specified one.
Here is the structure of the data:
{
"d": {
"results": [
{
"Id": 1,
"cost": "3",
"item": "Project 1",
"fiscalyear": "2014",
"reportmonth": "July"
}
]
}
}
Here is a sample of the desired, wanted results:
{
"Project 1": [
{
"date": "31-Jul-14",
"rating": "3"
},
{
"date": "31-Aug-14",
"rating": "4"
}
],
"Project 2": [
{
"date": "31-Jul-14",
"rating": "2"
}
]
}
This is my attempt:
var results = data.d.results;
var date;
var projectObj = {},
projectValues = {},
project = '';
var cost = '',
costStatus = '';
for (var i = 0, m = results.length; i < m; ++i) {
project = results[i]['item'];
if (!projectObj.hasOwnProperty(project)) {
projectObj[project] = [];
}
// use Moment to get and format date
date = moment(new Date(results[i]['reportmonth'] + ' 1,' + results[i]['fiscalyear'])).endOf('month').format('DD-MMM-YYYY');
// get cost for each unique project
costStatus = results[i]['cost'];
if (costStatus == null || costStatus == 'N/A') {
cost = 'N/A';
}
else {
cost = costStatus;
}
projectValues['rating'] = cost;
projectValues['date'] = date;
projectObj[project].push(projectValues);
}
Here is a Fiddle with the undesired, unwanted results:
https://jsfiddle.net/yh2134jn/4/
What am I doing wrong?
That is because You do not empty it new iteration. Try this:
for (var i = 0, m = results.length; i < m; ++i) {
projectValues = {};
project = results[i]['item'];
....
}
I got a json which looks like something like this :
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
For the moment I have something like that :
<script>
function myFunction() {
;
}
</script>
<div id = "short">
<button onclick="myFunction()">
short
</button>
</div>
My json is actually bigger than this example. I'd like to loop through it to get only the positions who are "short" and print them.
What is the best way to do that using only javascript ?
EDIT :
This is my new code but I still can't access to short or long position :
var stocks = [];
var longOnMarket = [];
var shortOnMarket = [];
var typeOfPosition = [];
var lolz = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
lolz.push(JSON.stringify(item));
stocks.push(key);
var json2 = json[item];
for (var key2 in json2) {
if (json2.hasOwnProperty(key2)) {
var longOrShort = json2[key2].positions;
typeOfPosition.push(JSON.stringify(longOrShort));
}
}
}
}
alert(stocks);
alert(lolz);
alert(typeOfPosition);
What you can do is
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
var object = JSON.parse(json);
for (var key in object) {
//Do your stuff
}
This solution looks for the array of positions and returns the object if some short is found.
var object = { "stock1": { "positions": [{ "date": "29/02/2016", "price": 15, "type": "short" }] }, "stock2": { "positions": [{ "date": "29/02/2016", "price": 20, "type": "long" }] } },
short = {};
Object.keys(object).forEach(function (k) {
if (object[k].positions.some(function (a) { return a.type === 'short' })) {
short[k] = object[k];
}
});
document.write('<pre>' + JSON.stringify(short, 0, 4) + '</pre>');
You should simple iterate through your object keys
var result = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
item.positions = item.positions.filter(function(el) { return el.type == 'short' });
result.push(item);
}
}
here is my try please check it out
var i,
shortTypePositionsArray = [],
shortTypeWholeObject = {};
$.each(json,function(key,value){
if(Object.keys(value) == "positions"){
for(i = 0;i<value.positions.length;i++){
if(value.positions[i].type == 'short')
{
shortTypePositionsArray.push(value.positions[i]);
shortTypeWholeObject[key] = value;
}
}
}
});
console.log(shortTypePositionsArray);
console.log(shortTypeWholeObject);
This is my output
[{ "MFG_NAME": "ABC", "CONCATED_MKT_SHARE": "01-SEP-14|0.59" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-MAY-14|0.87" },
{ "MFG_NAME": "ABC", "CONCATED_MKT_SHARE": "01-NOV-14|0.25" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-JUL-14|0.67" },
{ "MFG_NAME": "ABC", "CONCATED_MKT_SHARE": "01-DEC-14|0.10" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-OCT-14|0.03" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-DEC-14|0.14" }]
In this ABC has only data for 3 months SEP, NOV, DEC and XYZ has data for 4 months MAY, JUL, OCT, DEC. I am trying to fetch data from this output. But I am getting a problem while implementing it because of the months. In ABC there are only 3 months and the other 9 months are missing. Same in the case of XYZ there are 4 months and the other 8 months are missing. I am trying to replace these missing months with that month and the corresponding value to 0.0.
For example in ABC OCT is missing between the months I am trying to replace with 01-OCT-14|0.0 similar with all the cases. For this I have written the below code but its not working. Please correct the code.
var data = new Array();
data = ' [{ "MFG_NAME": "ABC", "CONCATED_MKT_SHARE": "01-SEP-14|0.59" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-MAY-14|0.87" },
{ "MFG_NAME": "ABC", "CONCATED_MKT_SHARE": "01-NOV-14|0.25" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-JUL-14|0.67" },
{ "MFG_NAME": "ABC", "CONCATED_MKT_SHARE": "01-DEC-14|0.10" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-OCT-14|0.03" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-DEC-14|0.14" }]';
var currentTime = new Date();//Sat Mar 21 2015 17:19:15 GMT+0530
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1; //Here I get the current month eg:MAR
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));//Here I get previous 12 months for comparision
//["APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
var MFG_NAME = [];
var DATE = [];
var MKT = [];
//The code to replace the months starts here
data.forEach(function(item) {
var share = item.CONCATED_MKT_SHARE;
for (var j = 0; j < dynmonths.length; j++) {
if (share.indexOf('-' + dynmonths[j] + '-') == -1) {
share += ',01-' + dynmonths[j] + '-14|0.0';
}
}// The months are replaced at the end, instead I want to replace it in order of the month names
//This is my actual implementation code where I get the output arrays DATE and MKT
var share = item.CONCATED_MKT_SHARE;
var parts = share.split("|");
var i = MFG_NAME.indexOf(item.MFG_NAME);
if (i == -1) {
MFG_NAME.push(item.MFG_NAME);
DATE.push([parts.shift()]);
MKT.push([+parts.shift()]);
}
else {
DATE[i].push(parts.shift());
MKT[i].push(+parts.shift());
}
});
I am getting the DATE and MKT but I am not getting the missing months
Expected output
DATE[0] = ["01-APR-14","01-MAY-14","01-JUN-14","01-JUL-14","01-AUG-14","01-SEP-14","01-OCT-14","01-NOV-14","01-DEC-14","01-JAN-14","01-FEB-14","01-MAR-14"];
DATE[1] = ["01-APR-14","01-MAY-14","01-JUN-14","01-JUL-14","01-AUG-14","01-SEP-14","01-OCT-14","01-NOV-14","01-DEC-14","01-JAN-14","01-FEB-14","01-MAR-14"];
MKT[0] = ["0.0","0.0","0.0","0.0","0.0","0.59","0.0","0.25","0.10","0.0","0.0","0.0"];
MKT[1] = [""0.0","0.75","0.0","0.67","0.0","0.0","0.03","0.0","0.14"]
I'd already started when #Learning posted his answer, so I just finished for an alternate take.
http://jsfiddle.net/bvaughn/ah4c0oah/3/
var data = [
{ "MFG_NAME": "ABC", "CONCATED_MKT_SHARE": "01-SEP-14|0.59" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-MAY-14|0.87" },
{ "MFG_NAME": "ABC", "CONCATED_MKT_SHARE": "01-NOV-14|0.25" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-JUL-14|0.67" },
{ "MFG_NAME": "ABC", "CONCATED_MKT_SHARE": "01-DEC-14|0.10" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-OCT-14|0.03" },
{ "MFG_NAME": "XYZ", "CONCATED_MKT_SHARE": "01-DEC-14|0.14" }
];
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var DATES = [[], []];
var MARKETS = [[], []];
function findDataForMonth(mfgName, month) {
for (var i = 0, length = data.length; i < length; i++) {
var datum = data[i];
if (datum.MFG_NAME === mfgName && datum.CONCATED_MKT_SHARE.indexOf(month) >= 0) {
return datum.CONCATED_MKT_SHARE.split('|')[1];
}
}
}
var monthsToCheck = [];
function addMonthsForYear(year, minMonth, maxMonth) {
for (var i = 0, length = monthNames.length; i < length; i++) {
if ((!minMonth || i >= minMonth) && (!maxMonth || i <= maxMonth)) {
monthsToCheck.push('01-' + monthNames[i] + '-' + year);
}
}
}
var monthOffset = new Date().getMonth();
addMonthsForYear(12, monthOffset);
addMonthsForYear(13);
addMonthsForYear(14);
addMonthsForYear(15, undefined, monthOffset);
for (var i = 0, length = monthsToCheck.length; i < length; i++) {
var month = monthsToCheck[i];
MARKETS[0].push(findDataForMonth("ABC", month) || 0.0);
MARKETS[1].push(findDataForMonth("XYZ", month) || 0.0);
DATES[0].push(month);
DATES[1].push(month);
}
console.log(DATES);
console.log(MARKETS);
I have created a solution, You can try this
var i=0;
for(var jo in pdata)
{
DATE.push([]);
MKT.push([]);
for(var mnt in monthNames)
{
var index = pdata[jo].m.indexOf("01-"+monthNames[mnt]+"-14");
if(index<0)
{
DATE[i].push("01-"+monthNames[mnt]+"-14");
MKT[i].push("0.0");
}
else{
DATE[i].push(pdata[jo].m[index]);
MKT[i].push(pdata[jo].v[index]);
}
}
i++;
}
var element = "";
for(i=0;i<DATE.length;i++)
{
element += DATE[i].join(", ");
element += "<br/>";
element += MKT[i].join(", ");
element += "<br/>";
}
Please check the fiddle here
I am working on application which I need to do grouping of different sets of javascript object and those will be based on month,day and year.
For day I am doing like below
var calculateByDay = function(inputList){
var outPutList = [];
var result = {}
var item = null, key = null;
for(i=0; c<inputList.length; i++) {
item=inputList[c];
key = Object.keys(item)[0];
item=item[key];
if(!result[key]) {
result[key] = item;
}
else {
result[key] += item;
}
for (r in result)
{
var docs = {};
docs["date"] = r;
docs["amount"] = result[r];
outPutList.push(docs);
}
}
return outPutList;
}
How can I improve above code and use it for month and year calculation also?
I went thorough underscore.js and it has a groupBy method. but seems not fits with my requirement.
I want to group by months and year also,
for
var inputList = [{"2012-12-02T00:00": 2000}, {"2013-01-01T00:00": 1200},{"2013-02-02T00:00": 550}, {"2013-02-02T00:00": 1000}];
The output should be:
Monthly :
[{"December 2012": 2000}, {"January 2013": 1200},{"February 2013": 1550}];
Yearly
[{"year 2012": 2000}, {"year 2013": 2750}];
And it seems I need to this kind of map,reduce approach for large data(array sets), is there any other library or practices I can do to make the code solid?
Thanks in advance.
Given a slightly different structure of data:
var data = [{
"date": "2011-12-02T00:00",
"value": 1000
}, {
"date": "2013-03-02T00:00",
"value": 1000
}, {
"date": "2013-03-02T00:00",
"value": 500
}, {
"date": "2012-12-02T00:00",
"value": 200
}, {
"date": "2013-04-02T00:00",
"value": 200
}, {
"date": "2013-04-02T00:00",
"value": 500
}, {
"date": "2013-03-02T00:00",
"value": 500
}, {
"date": "2013-04-12T00:00",
"value": 1000
}, {
"date": "2012-11-02T00:00",
"value": 600
}];
You could use underscore:
var grouped = _.groupBy(data, function(item) {
return item.date;
});
var groupedByYear = _.groupBy(data, function(item) {
return item.date.substring(0,4);
});
var groupedByMonth = _.groupBy(data, function(item) {
return item.date.substring(0,7);
});
console.log(groupedByYear);
See related answer: Javascript - underscorejs map reduce groupby based on date
Please see if the following refactor is useful for you
http://jsfiddle.net/wkUJC/
var dates = [{"2012-12-02T00:00": 2000}, {"2013-01-01T00:00": 1200},{"2013-02-02T00:00": 550}, {"2013-02-02T00:00": 1000}];
function calc(dates) {
var response = {};
dates.forEach(function(d){
for (var k in d) {
var _ = k.split("-");
var year = _[0]
var month = _[1]
if (!response[year]) response[year] = {total: 0}
response[year][month] = response[year][month] ? response[year][month]+d[k] : d[k]
response[year].total+= d[k]
}
});
console.log(response);
return response;
}
calc(dates);