Replacing a missing month using jquery - javascript

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

Related

Push Unique Objects to JavaScript Array

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'];
....
}

loop through json javascript

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);

javascript object manipulation using loop

[{
"name":"John"
"age":19,
"hobby":"Basketball;play computer"
},
{
"name":"Anderson"
"age":19,
"hobby":"Tennis"
}
]
John have 2 hobbies, it suppose to be in array but I have no control of the source of the api. How can I make the json to be below format?
[{
"name":"John"
"age":19,
"hobby":"Basketball"
},{
"name":"John"
"age":19,
"hobby":"play computer"
},
{
"name":"Anderson"
"age":19,
"hobby":"Tennis"
}
]
I'm new to jquery so here's code I've tried :
var hobbies = "";
$.each(json, function(){
hobbies = this.hobby.split(',');
});
var data = [{
"name": "John",
"age": 19,
"hobby": "Basketball;play computer"
}, {
"name": "Anderson",
"age": 19,
"hobby": "Tennis"
}]
$.each(data, function (index, value) {
if (value.hobby.split(';').length > 1) {
var dataArray = value.hobby.split(';');
value.hobby = dataArray[0];
dataArray.shift();
$.each(dataArray, function (innerIndex, innerValue) {
data.push({
"name": value.name,
"age": value.age,
"hobby": innerValue
});
});
}
});
console.log(data);
Fiddle Demo
var arr = [{
"name":"John",
"age":19,
"hobby":"Basketball;play computer"
},
{
"name":"Anderson",
"age":19,
"hobby":"Tennis"
}
];
$.each(arr, function(i,j){
var temp = j.hobby;
var hobby_arr = temp.split(';');
j.hobby = hobby_arr;
});
Try this. However there is an error in your provided json. There should be a ',' after the 'name' value
Here is a fiddle of your working thing ( assuming that ";" is the separator )
http://jsfiddle.net/swaprks/vcpq8dtr/
var json = [{
"name":"John",
"age":19,
"hobby":"Basketball;play computer"
},
{
"name":"Anderson",
"age":19,
"hobby":"Tennis"
}
];
$(function(){
for ( var i = 0; i < json.length; i++ ) {
var obj = json[i];
if ( obj["hobby"].indexOf(";") != -1 ){
var hobbyArr = obj["hobby"].split(";");
for ( var j = 0; j < hobbyArr.length; j++ ){
var newObj = {};
if ( j == 0 ){
json[i]["hobby"] = hobbyArr[j];
} else {
newObj = {
"name": obj["name"],
"age": obj["age"],
"hobby": hobbyArr[j]
}
json.push(newObj);
}
}
}
}
console.log(json)
});

How to fill dates in an array containing range of dates?

I have an array of dates containing a count value. e.g.
[
{
"date": "2014-11-11T08:00:00.000Z",
"count": 8
},
{
"date": "2014-11-13T08:00:00.000Z",
"count": 4
}
{
"date": "2014-11-16T08:00:00.000Z",
"count": 4
}
]
How do I fill in the missing dates with count = 0, to produce the following in javascript:
[
{
"date": "2014-11-11T08:00:00.000Z",
"count": 8
},
{
"date": "2014-11-12T08:00:00.000Z",
"count": 0
},
{
"date": "2014-11-13T08:00:00.000Z",
"count": 4
},
...
]
as you appear to be using momentjs
the first thing that came to mind was use the moment().add(number, units) and moment().diff(input, units, asFloat)
something like
var data = [
{
"date": "2014-11-11T08:00:00.000Z",
"count": 8
}, {
"date": "2014-11-16T08:00:00.000Z",
"count": 4
}
];
var startDate = moment(data[0].date);
var endDate = moment(data[1].date);
var days = endDate.diff(startDate, 'd', false);
alert(days);
for (var i = 1; i < days; i++) {
data.splice(i,0, {"date" : startDate.add(1, 'd').toISOString(), 'count': 0 })
}
for (var i = 0; i < data.length; i++) {
alert(data[i].date);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.min.js"></script>
Try this:
var arr = [
{
"date": "2014-11-11T08:00:00.000Z",
"count": 8
},
{
"date": "2014-11-16T08:00:00.000Z",
"count": 4
}
];
function fillDates(start, end) {
var output = [start];
var date = new Date(start.date);
var endDate = new Date(end.date);
do {
output.push({
"date": date.toISOString(),
"count": 0
});
date = new Date(date.getTime());
date.setDate(date.getDate() + 1);
} while (date < endDate);
output.push(end);
return output;
}
var start = arr[0];
var end = arr[1];
fillDates(start, end);
const models = [
{
date: '2018-10-17',
value: 3,
},
{
date: '2018-10-20',
value: 4,
},
{
date: '2018-10-21',
value: 5,
},
{
date: '2018-10-27',
value: 6,
},
];
const filledInDates = models.reduce((newArray, currentModel, index, originalArray) => {
const nextModel = originalArray[index + 1];
if (nextModel) {
const currentDate = moment(currentModel.date);
const daysBetween = moment(nextModel.date).diff(currentDate, 'days');
const fillerDates = Array.from({length: daysBetween - 1}, (value, dayIndex) => {
return {
value: currentModel.value,
date: moment(currentDate).add(dayIndex + 1, 'days').format('YYYY-MM-DD'),
};
});
newArray.push(currentModel, ...fillerDates);
} else {
newArray.push(currentModel);
}
return newArray;
}, []);
console.log(filledInDates);
Output:
[
{value:3, date:"2018-10-17"},
{value:3, date:"2018-10-18"},
{value:3, date:"2018-10-19"},
{value:4, date:"2018-10-20"},
{value:5, date:"2018-10-21"},
{value:5, date:"2018-10-22"},
{value:5, date:"2018-10-23"},
{value:5, date:"2018-10-24"},
{value:5, date:"2018-10-25"},
{value:5, date:"2018-10-26"},
{value:6, date:"2018-10-27"}
]

difficulties in JSON forming

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?

Categories