how could i change the string data format ..? - javascript

The data format, which I get from back-end is
{
"2020-08-22": 1425,
"2020-08-23": 1475,
"2020-08-24": 1475,
"flightnumber": "EK-853",
"source": "emirates",
"stops": "stops-0"
}
Is that possible to change the key data as following
{
"Aug 22": 1425,
"Aug 23": 1475,
"Aug 24": 1475,
"flightnumber": "EK-853",
"source": "emirates",
"stops": "stops-0"
}
Please tell me some solution for this.

Below snippet could help you. It has several things to notice:
iterate through object's keys
object's dynamic key
detect invalid date
const data = {
"2020-08-22": 1425,
"2020-08-23": 1475,
"2020-08-24": 1475,
flightnumber: "EK-853",
source: "emirates",
stops: "stops-0",
}
const monthNames = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
const res = {}
Object.keys(data).forEach((k) => {
const date = new Date(k)
if (!isNaN(date.getTime())) {
res[`${monthNames[date.getMonth()]} ${date.getDate()}`] = data[k]
} else {
res[k] = data[k]
}
})
console.log(res)

Related

JS group by month/year of date

I have an array with date and id's I want to convert it group by month and by year year
oldest date/month should be at first
let myArray = [
{project_id: 444, date: "2021-08-17 14:33:49"},
{project_id: 444, date: "2021-08-16 14:33:50"},
{project_id: 555, date: "2020-08-16 14:33:50"},
{project_id: 666, date: "2020-08-17 12:33:50"},
{project_id: 666, date: "2020-09-17 12:33:50"},
{project_id: 666, date: "2020-09-17 12:33:50"},
];
The below array is my actual requirement that is manually converted from the above array
eg:
[
{
"month_year": "Aug 2020",
"data": [
{
"date": "2020-08-16 14:33:50",
"project_id": 666
},
{
"date": "2020-08-17 12:33:50",
"project_id": 777
}
]
},
{
"month_year": "Sep 2020",
"data": [
{
"date": "22020-09-17 12:33:50",
"project_id": 666
},
{
"date": "2020-09-17 12:33:50",
"project_id": 666
}
]
},
{
"month_year": "Aug 2021",
"data": [
{
"date": "2021-08-17 14:33:49",
"project_id": 444
},
{
"date": "2021-08-16 14:33:50",
"project_id": 444
}
]
},
]
Something like this should work:
function groupByDate(list) {
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
let result = [];
for (let obj of list) {
let objDate = new Date(obj.date);
let monthYear = `${monthNames[objDate.getMonth()]} ${objDate.getFullYear()}`;
let foundMatch = false;
for (let i = 0; i < result.length; i++) {
if (result[i].month_year === monthYear) {
result[i].data.push(obj);
foundMatch = true;
break;
}
}
if (!foundMatch) {
result.push({
"month_year": monthYear,
"data": [obj]
});
}
}
return result;
}
Basically it loops over each object in the list, and if the current date (month and year only) hasn't already been processed, it will add another json object to the result list. If the current date have been processed before, it adds it to the correct json.
Working JSFiddle:
https://jsfiddle.net/dfhg41sx/1/

Mapping object to array in js

I am beginner in data structure and trying to improve my skills.
I am trying to divide the object value to list of other object.
So I/P is
1st Object JSON:
let mapMonth ={
"10": 8,
"11": 30,
"12": 31,
"01": 23
}
where 10 is Oct, 11 is Nov, 12 is Dec and 01 is Jan.
2nd Object JSON:
let mapData = {
"key1": {
"subkey1": [
[407341537, 1666737463, 363248139, 596560162]
],
"subkey2": ["Oct", "Nov", "Dec", "Jan"]
},
"key2": {
"subkey1": [
[78491802, 334718068, 68299710, 81365082]
],
"subkey2": ["Oct", "Nov", "Dec", "Jan"]
},
"key3": {
"subkey1": [
[501844, 3362217, 648527, 1073573]
],
"subkey2": ["Oct", "Nov", "Dec", "Jan"]
}
}
So now I need to divide 407341537 with 8 i.e 50917692.125, 1666737463 with 30 i.e 55557915.4333 and so on..
Expected output:
{
"key1": {
"subkey1": [
[50917692.125, 55557915.4333, 11717681.9,72466846.2174]
],
"subkey2": ["Oct", "Nov", "Dec", "Jan"]
},
"key2": {
"subkey1": [
[9811475.25, 11157268.9333, 2203216.45161, 3537612.26087]
],
"subkey2": ["Oct", "Nov", "Dec", "Jan"]
},
"key3": {
"subkey1": [
[62730.5, 112073.9, 20920.225, 46677.086]
],
"subkey2": ["Oct", "Nov", "Dec", "Jan"]
}
}
Code I have tried:
let averageObj = {};
var count = 0;
for (let key in mapData) {
averageObj[key] = [];
mapData[key]['subkey1'][0].forEach((data, index) => {
for (let monthKey in mapMonth) {
averageObj[key].push(data / mapMonth[monthKey]);
}
});
}
Please let me know if you need anything else.
Assuming an object with fixed keys and nested array with only one index:
This approach mutates the original object.
let mapMonthDesc = {"Oct": "10","Nov": "11","Dec": "12","Jan": "01"},
mapMonth = {"10": 8,"11": 30,"12": 31,"01": 23},
mapData = {"key1": {"subkey1": [[407341537, 1666737463, 363248139, 596560162]],"subkey2": ["Oct", "Nov", "Dec", "Jan"]},"key2": {"subkey1": [[78491802, 334718068, 68299710, 81365082]],"subkey2": ["Oct", "Nov", "Dec", "Jan"]},"key3": {"subkey1": [[501844, 3362217, 648527, 1073573]],"subkey2": ["Oct", "Nov", "Dec", "Jan"]}};
Object.values(mapData).forEach(({subkey1: [numbers], subkey2}) => {
numbers.forEach((n, i) => numbers[i] = n / mapMonth[mapMonthDesc[subkey2[i]]]);
});
console.log(mapData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

What is the proper way to match key and value to some variable using Javascript array?

I'm trying to create a function in javascript in order to get a value that match an external variable.
I created an array of key/value. Then I made a function that will check if a value match to a variable. Then i will return the key of this value.
function findNumberFromMonth($data)
{
var obj = {
01: "Jan",
02: "Feb",
03: "Mar",
04: "Apr",
05: "May",
06: "Jun",
07: "Jul",
08: "Aug",
09: "Sep",
10: "Oct",
11: "Nov",
12: "Dec"
}
for(var element in obj)
{
if($data == element.value )
{
$number = element.key
}
return $number;
}
}
I expected the output of "01" if i initialize $data as "Jan".
But i only got an undefined object.
How may i process ?
Thank you for your replies.
This can be done with find and Object.entries:
function findNumberFromMonth(data) {
const months = {
01: "Jan",
02: "Feb",
03: "Mar",
04: "Apr",
05: "May",
06: "Jun",
07: "Jul",
08: "Aug",
09: "Sep",
10: "Oct",
11: "Nov",
12: "Dec"
};
return Object.entries(months).find(([key, val]) => data === val)[0];
}
console.log(findNumberFromMonth('Oct'));
you can do this.
var obj = {
01: "Jan",
02: "Feb",
03: "Mar",
04: "Apr",
05: "May",
06: "Jun",
07: "Jul",
08: "Aug",
09: "Sep",
10: "Oct",
11: "Nov",
12: "Dec"
}
var key = Object.keys(obj)[Object.values(obj).indexOf("Jun")]
console.log(key)
If what you want to do is map month names to month numbers, your object is backwards:
function findNumberFromMonth($data)
{
var months = {
"Jan": "01",
"Feb": "02",
"Mar": "03",
// ...
};
return months[$data];
}
if you need both keys and values simultaneously, use object.entries and iterate over it.
const data = "Feb";
const obj = {
"01": "Jan",
"02": "Feb",
"03": "Mar",
"04": "Apr",
"05": "May",
"06": "Jun",
"07": "Jul",
"08": "Aug",
}
for (let [key, value] of Object.entries(obj)) {
if(data === value )
{
console.log(key);
}
}
When you use for(let x in obj) x is the key of the object.for...in.
function findNumberFromMonth($data)
{
var obj = {
01: "Jan",
02: "Feb",
03: "Mar",
04: "Apr",
05: "May",
06: "Jun",
07: "Jul",
08: "Aug",
09: "Sep",
10: "Oct",
11: "Nov",
12: "Dec"
}
for(var key in obj)
{
if($data == obj[key]) return key;
}
}
console.log(findNumberFromMonth('Jan'));
You assign $number variable in if statement. But return it in out of if statement. You must move return line to if statement and if not returned anything, you can return false value.
function findNumberFromMonth($data) {
var obj = {
01: "Jan",
02: "Feb",
03: "Mar",
04: "Apr",
05: "May",
06: "Jun",
07: "Jul",
08: "Aug",
09: "Sep",
10: "Oct",
11: "Nov",
12: "Dec"
}
for (var key in obj) {
if ($data === obj[key])
return key;
}
return false;
}
console.log(findNumberFromMonth('Mar'));

Replace the decimal dot with a comma on an axis in D3?

This is about the ticks on axes in D3: Is there a way to replace the decimal dot with a comma in numbers? I want the numbers to be displayed like this (which is normal in Germany, such a big number is just for demonstration)
1.000.000,1 // This is one million and a tenth
and not like this:
1,000,000.1
I've read the documentation about the topic, but it seems like there is no possibility!? That's my relevant code so far:
localeFormatter = d3.locale({
"decimal": ".",
"thousands": ",",
"grouping": [3],
"currency": ["", "€"],
"dateTime": "%a, %e %b %Y, %X",
"date": "%d.%m.%Y",
"time": "%H:%M:%S",
"periods": ["", ""],
"days": ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
"shortDays": ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
"months": ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
"shortMonths": ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"]
});
numberFormat = localeFormatter.numberFormat("04.,"); // The setting is applied, but has not the desired effect...
yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(numberFormat);
Using the following settings for d3.locale:
var localeFormatter = d3.locale({
"decimal": ",",
"thousands": ".",
...
});
Note that I have changed the . in , and vice versa. And with:
var numberFormat = localeFormatter.numberFormat(",.2f");
I print the number using a thousands separator , (it uses a . as defined in the locale) and two digits after the comma .2f:
console.log(numberFormat(1000000.1)); // "1.000.000,10"

Bootstrap datepicker error when using other language: Uncaught TypeError: Cannot read property 'length' of undefined

I'm using the datepicker from Bootstrap (http://bootstrap-datepicker.readthedocs.org/en/latest/i18n.html). When using datepicker without the "language" property, it works, but when I try to specify a language ("sv"), it fails with the message (i.e when trying to select a date in the widget):
Uncaught TypeError: Cannot read property 'length' of undefined
These are the versions I'm using:
jQuery v1.8.3
jQuery UI 1.8.22
Boostrap 2.3.1
From looking at the debugger it seems that this is the code that crashes (Datetimepicker.prototype, the row with "p: "):
formatDate: function (date, format, language, type) {
if (date == null) {
return '';
}
var val;
if (type == 'standard') {
val = {
// year
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear(),
// month
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
// day
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
p: (dates[language].meridiem.length == 2 ? dates[language].meridiem[date.getUTCHours() < 12 ? 0 : 1] : ''),
// hour
h: date.getUTCHours(),
// minute
i: date.getUTCMinutes(),
// second
s: date.getUTCSeconds()
};
This is the working code (a widget in english):
var dates = $('#date-picker input[name=from_date], .facet-container input[name=to_date]').datetimepicker({
format: 'yyyy-mm-dd',
autoclose:'true',
todayBtn:'true',
pickerPosition:'bottom-left',
minView:'month'
}).on('changeDate', function(ev){
});
This crashes:
$.fn.datetimepicker.dates['sv'] = {
days: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"],
daysShort: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"],
daysMin: ["Sö", "Må", "Ti", "On", "To", "Fr", "Lö"],
months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Idag",
clear: "Rensa"
};
var dates = $('#date-picker input[name=from_date], .facet-container input[name=to_date]').datetimepicker({
format: 'yyyy-mm-dd',
autoclose:'true',
weekStart: 1,
language:'sv',
todayBtn:'true',
pickerPosition:'bottom-left',
minView:'month'
}).on('changeDate', function(ev){
});
What could be the problem??
This fixed it, i.e had to add a "meridiem" property:
$.fn.datetimepicker.dates['sv'] = {
days: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"],
daysShort: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"],
daysMin: ["Sö", "Må", "Ti", "On", "To", "Fr", "Lö"],
months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
meridiem: '',
today: "Idag",
clear: "Rensa"
};

Categories

Resources