destructuring - error duplicate declaration 'hour' - javascript

I am using destructuring to create a start and end time:
const {
startYear: year,
startMonth: month,
startDay: day,
startHour: hour,
startMinute: minute
} = event.start_date_details;
const {
endHour: hour,
endMinute: minute
} = event.end_date_details;
Any ideas?
Events json:
"events": [
{
"id": 518,
"global_id": "wordpress.rguc.co.uk?id=518",
"global_id_lineage": [
"wordpress.rguc.co.uk?id=518"
],
"author": "1",
"status": "publish",
"date": "2017-12-14 12:11:42",
"date_utc": "2017-12-14 12:11:42",
"modified": "2018-01-11 10:04:49",
"modified_utc": "2018-01-11 10:04:49",
"url": "http://wordpress.rguc.co.uk/event/another-one/",
"rest_url": "http://wordpress.rguc.co.uk/wp-json/tribe/events/v1/events/518",
"title": "another one",
"description": "",
"excerpt": "",
"image": false,
"all_day": true,
"start_date": "2018-01-31 00:00:00",
"start_date_details": {
"year": "2018",
"month": "01",
"day": "31",
"hour": "00",
"minutes": "00",
"seconds": "00"
},
"end_date": "2018-01-31 23:59:59",
"end_date_details": {
"year": "2018",
"month": "01",
"day": "31",
"hour": "23",
"minutes": "59",
"seconds": "59"
},
"utc_start_date": "2018-01-31 00:00:00",
"utc_start_date_details": {
"year": "2018",
"month": "01",
"day": "31",
"hour": "00",
"minutes": "00",
"seconds": "00"
},
"utc_end_date": "2018-01-31 23:59:59",
"utc_end_date_details": {
"year": "2018",
"month": "01",
"day": "31",
"hour": "23",
"minutes": "59",
"seconds": "59"
},

The syntax for destructuring (BTW destructing is the wrong term) is different. You need to specify keys you match before colon and variables you declare after colon.
Maybe you wanted:
const {
year: startYear,
month: startMonth,
day: startDay,
hour: startHour,
minutes: startMinute
} = event.start_date_details;
const {
hour: endHour,
minutes: endMinute
} = event.end_date_details;

You're destructuring both event.start_date_details.startHour and event.end_date_details.endHour to const hour. Change it to
const {
start_date_details: {
year: startYear,
month: startMonth,
day: startDay,
hour: startHour,
minutes: startMinute
},
end_date_details: {
hour: endHour,
minutes: endMinute
}
} = event;
so that you have the variable startHour, startMinute, endHour, and endMinute instead mapped from event.(start/end)_date_details.(hour/minutes).
See MDN's Destructuring Assignment - Assigning to new variable names.

Related

Selection from JSON

I recently started learning JavaScript and faced a task that I can't complete in any way, every time I get the wrong data that I need
There is an object that contains data on banking transactions, I need to make a selection and form a new object using filter, map or reduce:
We assume that the initial balance on the card = 0.
Output the TOP 3 months with the largest number of operations by month.
Formalize it as a task_1(arr) function, where arr is the source array with data
for all months.
Output format:
[
{ year: 2019, month: 11, opsCount: 27 },
{ year: 2019, month: 10, opsCount: 26 },
{ year: 2019, month: 8, opsCount: 24 }
]
Output statistics for the end of the specified month.
monthmonthBalance - own balance by month = The amount of all
deposits minus the amount of all debits
montWithdrawal – total cash withdrawal amount
withdrawalRate – the share of the total amount of debits from the total amount of
deposits per month.
rank – user status calculated by the formula:
Gold if withdrawalRate < 0.15.
Silver if withdrawalRate < 0.3.
Bronze in all other cases.
Formalize it as a task_2(year, month, arr) function, where year, month is the desired one
month, and arr is the original array with all the data by month.
Output format:
{
date: '2019-01-31’,
monthBalance: 3829,
monthWithrawal: 33800,
withdrawalRate: 0.3133
rank: 'Bronze’
}
Calculate statistics from task 2 for all months of the period.
Add a field to each month
totalBalance - cumulative balance = Own balance for the
month + Balance for the cumulative balance for the previous month.
Output format:
[
{
date: '2019-01-31’,
monthBalance: 3829,
totalBalance: 3829,
monthWithrawal: 33800,
withdrawalRate: 0.3133
rank: ’Bronze'
},
...
]
Formalize it as a task_3(arr) function, where arr is the source array with data.
JSON with data:
[
{ "year": 2019, "month": 1, "day": 1, "type": "replenishment", "amount": 79817 },
{ "year": 2019, "month": 1, "day": 3, "type": "payment", "amount": 11334 },
{ "year": 2019, "month": 1, "day": 5, "type": "withdrawal", "amount": 26700 },
{ "year": 2019, "month": 1, "day": 5, "type": "payment", "amount": 15475 },
{ "year": 2019, "month": 1, "day": 6, "type": "payment", "amount": 4818 },
{ "year": 2019, "month": 1, "day": 6, "type": "payment", "amount": 1893 },
{ "year": 2019, "month": 1, "day": 7, "type": "payment", "amount": 3844 },
{ "year": 2019, "month": 1, "day": 7, "type": "withdrawal", "amount": 3100 },
{ "year": 2019, "month": 1, "day": 7, "type": "payment", "amount": 3230 },
{ "year": 2019, "month": 1, "day": 7, "type": "payment", "amount": 2427 },
{ "year": 2019, "month": 1, "day": 9, "type": "replenishment", "amount": 15835 },
{ "year": 2019, "month": 1, "day": 10, "type": "payment", "amount": 9670 },
{ "year": 2019, "month": 1, "day": 11, "type": "payment", "amount": 582 },
{ "year": 2019, "month": 1, "day": 11, "type": "withdrawal", "amount": 1100 },
{ "year": 2019, "month": 1, "day": 11, "type": "replenishment", "amount": 5971 },
{ "year": 2019, "month": 1, "day": 12, "type": "payment", "amount": 173 },
{ "year": 2019, "month": 1, "day": 14, "type": "withdrawal", "amount": 1500 },
{ "year": 2019, "month": 1, "day": 14, "type": "payment", "amount": 3641 },
{ "year": 2019, "month": 1, "day": 16, "type": "payment", "amount": 4669 },
{ "year": 2019, "month": 1, "day": 18, "type": "payment", "amount": 2460 },
{ "year": 2019, "month": 1, "day": 19, "type": "payment", "amount": 1307 },
{ "year": 2019, "month": 1, "day": 20, "type": "withdrawal", "amount": 1400 },
{ "year": 2019, "month": 1, "day": 21, "type": "payment", "amount": 952 },
{ "year": 2019, "month": 1, "day": 21, "type": "payment", "amount": 561 },
{ "year": 2019, "month": 1, "day": 21, "type": "replenishment", "amount": 6236 },
{ "year": 2019, "month": 1, "day": 22, "type": "payment", "amount": 888 },
{ "year": 2019, "month": 1, "day": 22, "type": "payment", "amount": 2306 },
{ "year": 2019, "month": 2, "day": 1, "type": "replenishment", "amount": 84839 },
{ "year": 2019, "month": 2, "day": 1, "type": "withdrawal", "amount": 27700 },
{ "year": 2019, "month": 2, "day": 1, "type": "payment", "amount": 11145 },
{ "year": 2019, "month": 2, "day": 2, "type": "payment", "amount": 4075 },
{ "year": 2019, "month": 2, "day": 4, "type": "withdrawal", "amount": 10900 },
{ "year": 2019, "month": 2, "day": 6, "type": "payment", "amount": 10537 },
{ "year": 2019, "month": 2, "day": 6, "type": "payment", "amount": 6001 },
{ "year": 2019, "month": 2, "day": 7, "type": "withdrawal", "amount": 7300 },
{ "year": 2019, "month": 2, "day": 10, "type": "withdrawal", "amount": 1500 },
{ "year": 2019, "month": 2, "day": 10, "type": "payment", "amount": 3584 },
{ "year": 2019, "month": 2, "day": 11, "type": "payment", "amount": 701 },
{ "year": 2019, "month": 3, "day": 1, "type": "replenishment", "amount": 84771 },
{ "year": 2019, "month": 3, "day": 3, "type": "withdrawal", "amount": 22700 },
{ "year": 2019, "month": 3, "day": 5, "type": "payment", "amount": 12352 },
{ "year": 2019, "month": 3, "day": 8, "type": "payment", "amount": 2795 },
{ "year": 2019, "month": 3, "day": 11, "type": "withdrawal", "amount": 16600 },
{ "year": 2019, "month": 3, "day": 11, "type": "replenishment", "amount": 4141 },
{ "year": 2019, "month": 3, "day": 11, "type": "payment", "amount": 9854 },
{ "year": 2019, "month": 3, "day": 13, "type": "withdrawal", "amount": 1200 },
{ "year": 2019, "month": 3, "day": 14, "type": "payment", "amount": 11573 },
{ "year": 2019, "month": 3, "day": 14, "type": "payment", "amount": 5138 },
{ "year": 2019, "month": 3, "day": 15, "type": "payment", "amount": 731 },
{ "year": 2019, "month": 3, "day": 17, "type": "payment", "amount": 5053 },
{ "year": 2019, "month": 3, "day": 19, "type": "withdrawal", "amount": 400 },
{ "year": 2019, "month": 3, "day": 20, "type": "payment", "amount": 1745 },
{ "year": 2019, "month": 3, "day": 20, "type": "payment", "amount": 602 },
{ "year": 2019, "month": 3, "day": 21, "type": "payment", "amount": 178 },
{ "year": 2019, "month": 3, "day": 22, "type": "payment", "amount": 353 },
{ "year": 2019, "month": 3, "day": 23, "type": "payment", "amount": 837 },
{ "year": 2019, "month": 3, "day": 23, "type": "payment", "amount": 330 },
{ "year": 2019, "month": 3, "day": 23, "type": "payment", "amount": 799 },
{ "year": 2019, "month": 3, "day": 24, "type": "payment", "amount": 294 },
{ "year": 2019, "month": 3, "day": 24, "type": "payment", "amount": 260 },
{ "year": 2019, "month": 3, "day": 25, "type": "withdrawal", "amount": 200 },
{ "year": 2019, "month": 4, "day": 1, "type": "replenishment", "amount": 88656 },
{ "year": 2019, "month": 4, "day": 4, "type": "payment", "amount": 37852 },
{ "year": 2019, "month": 4, "day": 7, "type": "payment", "amount": 9365 },
{ "year": 2019, "month": 4, "day": 8, "type": "payment", "amount": 16701 },
{ "year": 2019, "month": 4, "day": 11, "type": "payment", "amount": 8979 },
{ "year": 2019, "month": 4, "day": 11, "type": "payment", "amount": 1971 },
{ "year": 2019, "month": 4, "day": 13, "type": "payment", "amount": 1261 },
{ "year": 2019, "month": 4, "day": 13, "type": "withdrawal", "amount": 800 },
{ "year": 2019, "month": 4, "day": 15, "type": "payment", "amount": 5553 },
{ "year": 2019, "month": 4, "day": 17, "type": "payment", "amount": 2593 },
{ "year": 2019, "month": 4, "day": 18, "type": "replenishment", "amount": 6915 },
{ "year": 2019, "month": 4, "day": 19, "type": "replenishment", "amount": 17647 },
{ "year": 2019, "month": 4, "day": 21, "type": "payment", "amount": 13814 },
{ "year": 2019, "month": 4, "day": 22, "type": "payment", "amount": 2707 },
{ "year": 2019, "month": 4, "day": 22, "type": "withdrawal", "amount": 1300 },
{ "year": 2019, "month": 4, "day": 22, "type": "withdrawal", "amount": 2900 },
{ "year": 2019, "month": 4, "day": 23, "type": "replenishment", "amount": 10709 },
{ "year": 2019, "month": 4, "day": 23, "type": "payment", "amount": 686 },
{ "year": 2019, "month": 4, "day": 23, "type": "withdrawal", "amount": 5100 },
{ "year": 2019, "month": 4, "day": 23, "type": "payment", "amount": 3830 },
{ "year": 2019, "month": 5, "day": 1, "type": "replenishment", "amount": 59877 },
{ "year": 2019, "month": 5, "day": 2, "type": "payment", "amount": 14095 },
{ "year": 2019, "month": 5, "day": 5, "type": "payment", "amount": 10858 },
{ "year": 2019, "month": 5, "day": 8, "type": "payment", "amount": 9412 },
{ "year": 2019, "month": 5, "day": 11, "type": "replenishment", "amount": 6892 },
{ "year": 2019, "month": 5, "day": 11, "type": "payment", "amount": 17541 },
{ "year": 2019, "month": 5, "day": 11, "type": "payment", "amount": 2666 },
{ "year": 2019, "month": 5, "day": 11, "type": "payment", "amount": 3935 },
{ "year": 2019, "month": 5, "day": 12, "type": "withdrawal", "amount": 2600 },
{ "year": 2019, "month": 5, "day": 14, "type": "payment", "amount": 2096 },
{ "year": 2019, "month": 5, "day": 14, "type": "replenishment", "amount": 2733 },
{ "year": 2019, "month": 5, "day": 15, "type": "replenishment", "amount": 538 },
{ "year": 2019, "month": 5, "day": 15, "type": "payment", "amount": 5324 },
{ "year": 2019, "month": 5, "day": 15, "type": "payment", "amount": 2490 },
{ "year": 2019, "month": 5, "day": 15, "type": "payment", "amount": 3510 },
{ "year": 2019, "month": 5, "day": 17, "type": "withdrawal", "amount": 300 },
{ "year": 2019, "month": 5, "day": 17, "type": "payment", "amount": 133 },
{ "year": 2019, "month": 6, "day": 1, "type": "replenishment", "amount": 89064 },
{ "year": 2019, "month": 6, "day": 2, "type": "payment", "amount": 7613 },
{ "year": 2019, "month": 6, "day": 2, "type": "payment", "amount": 33742 },
{ "year": 2019, "month": 6, "day": 5, "type": "withdrawal", "amount": 7200 },
{ "year": 2019, "month": 6, "day": 6, "type": "payment", "amount": 15125 },
{ "year": 2019, "month": 6, "day": 9, "type": "payment", "amount": 3379 },
{ "year": 2019, "month": 6, "day": 10, "type": "payment", "amount": 1260 },
{ "year": 2019, "month": 6, "day": 12, "type": "payment", "amount": 11066 },
{ "year": 2019, "month": 6, "day": 12, "type": "replenishment", "amount": 7050 },
{ "year": 2019, "month": 6, "day": 12, "type": "payment", "amount": 7531 },
{ "year": 2019, "month": 6, "day": 13, "type": "payment", "amount": 4776 },
{ "year": 2019, "month": 6, "day": 13, "type": "replenishment", "amount": 4456 },
{ "year": 2019, "month": 6, "day": 14, "type": "replenishment", "amount": 7998 },
{ "year": 2019, "month": 6, "day": 16, "type": "payment", "amount": 2437 },
{ "year": 2019, "month": 6, "day": 16, "type": "replenishment", "amount": 11729 },
{ "year": 2019, "month": 6, "day": 18, "type": "payment", "amount": 11216 },
{ "year": 2019, "month": 6, "day": 19, "type": "payment", "amount": 3420 },
{ "year": 2019, "month": 6, "day": 19, "type": "payment", "amount": 1339 },
{ "year": 2019, "month": 6, "day": 20, "type": "payment", "amount": 5578 },
{ "year": 2019, "month": 6, "day": 21, "type": "withdrawal", "amount": 1600 },
{ "year": 2019, "month": 6, "day": 21, "type": "withdrawal", "amount": 400 },
{ "year": 2019, "month": 7, "day": 1, "type": "replenishment", "amount": 51749 },
{ "year": 2019, "month": 7, "day": 2, "type": "payment", "amount": 2875 },
{ "year": 2019, "month": 7, "day": 2, "type": "payment", "amount": 10315 },
{ "year": 2019, "month": 7, "day": 5, "type": "payment", "amount": 18501 },
{ "year": 2019, "month": 7, "day": 5, "type": "payment", "amount": 12728 },
{ "year": 2019, "month": 7, "day": 7, "type": "payment", "amount": 4505 },
{ "year": 2019, "month": 7, "day": 8, "type": "payment", "amount": 2758 },
{ "year": 2019, "month": 7, "day": 8, "type": "payment", "amount": 60 },
{ "year": 2019, "month": 7, "day": 10, "type": "withdrawal", "amount": 1100 },
{ "year": 2019, "month": 7, "day": 12, "type": "withdrawal", "amount": 1000 },
{ "year": 2019, "month": 7, "day": 13, "type": "payment", "amount": 151 },
{ "year": 2019, "month": 8, "day": 1, "type": "replenishment", "amount": 85156 },
{ "year": 2019, "month": 8, "day": 1, "type": "payment", "amount": 33978 },
{ "year": 2019, "month": 8, "day": 2, "type": "payment", "amount": 6548 },
{ "year": 2019, "month": 8, "day": 3, "type": "payment", "amount": 5909 },
{ "year": 2019, "month": 8, "day": 6, "type": "payment", "amount": 2326 },
{ "year": 2019, "month": 8, "day": 6, "type": "payment", "amount": 17798 },
{ "year": 2019, "month": 8, "day": 9, "type": "replenishment", "amount": 10770 },
{ "year": 2019, "month": 8, "day": 10, "type": "withdrawal", "amount": 7400 },
{ "year": 2019, "month": 8, "day": 12, "type": "payment", "amount": 6065 },
{ "year": 2019, "month": 8, "day": 14, "type": "withdrawal", "amount": 900 },
{ "year": 2019, "month": 8, "day": 14, "type": "withdrawal", "amount": 1400 },
{ "year": 2019, "month": 8, "day": 14, "type": "payment", "amount": 4673 },
{ "year": 2019, "month": 8, "day": 15, "type": "payment", "amount": 960 },
{ "year": 2019, "month": 8, "day": 15, "type": "payment", "amount": 1085 },
{ "year": 2019, "month": 8, "day": 17, "type": "payment", "amount": 3723 },
{ "year": 2019, "month": 8, "day": 17, "type": "payment", "amount": 2522 },
{ "year": 2019, "month": 8, "day": 19, "type": "replenishment", "amount": 2496 },
{ "year": 2019, "month": 8, "day": 20, "type": "payment", "amount": 876 },
{ "year": 2019, "month": 8, "day": 20, "type": "payment", "amount": 2504 },
{ "year": 2019, "month": 8, "day": 21, "type": "payment", "amount": 826 },
{ "year": 2019, "month": 8, "day": 22, "type": "payment", "amount": 768 },
{ "year": 2019, "month": 8, "day": 23, "type": "withdrawal", "amount": 700 },
{ "year": 2019, "month": 8, "day": 23, "type": "payment", "amount": 190 },
{ "year": 2019, "month": 8, "day": 24, "type": "payment", "amount": 235 },
{ "year": 2019, "month": 9, "day": 1, "type": "replenishment", "amount": 95512 },
{ "year": 2019, "month": 9, "day": 3, "type": "payment", "amount": 26758 },
{ "year": 2019, "month": 9, "day": 3, "type": "replenishment", "amount": 8377 },
{ "year": 2019, "month": 9, "day": 4, "type": "payment", "amount": 30865 },
{ "year": 2019, "month": 9, "day": 4, "type": "withdrawal", "amount": 12800 },
{ "year": 2019, "month": 9, "day": 7, "type": "payment", "amount": 10518 },
{ "year": 2019, "month": 9, "day": 8, "type": "payment", "amount": 11007 },
{ "year": 2019, "month": 9, "day": 10, "type": "payment", "amount": 5613 },
{ "year": 2019, "month": 9, "day": 10, "type": "withdrawal", "amount": 1700 },
{ "year": 2019, "month": 9, "day": 12, "type": "payment", "amount": 2237 },
{ "year": 2019, "month": 9, "day": 14, "type": "payment", "amount": 885 },
{ "year": 2019, "month": 9, "day": 14, "type": "payment", "amount": 977 },
{ "year": 2019, "month": 9, "day": 15, "type": "payment", "amount": 766 },
{ "year": 2019, "month": 9, "day": 17, "type": "payment", "amount": 360 },
{ "year": 2019, "month": 9, "day": 18, "type": "payment", "amount": 116 },
{ "year": 2019, "month": 9, "day": 18, "type": "withdrawal", "amount": 200 },
{ "year": 2019, "month": 9, "day": 19, "type": "payment", "amount": 115 },
{ "year": 2019, "month": 9, "day": 20, "type": "payment", "amount": 50 },
{ "year": 2019, "month": 9, "day": 21, "type": "payment", "amount": 32 },
{ "year": 2019, "month": 10, "day": 1, "type": "replenishment", "amount": 90475 },
{ "year": 2019, "month": 10, "day": 1, "type": "replenishment", "amount": 8845 },
{ "year": 2019, "month": 10, "day": 2, "type": "payment", "amount": 7121 },
{ "year": 2019, "month": 10, "day": 3, "type": "payment", "amount": 27955 },
{ "year": 2019, "month": 10, "day": 3, "type": "payment", "amount": 23079 },
{ "year": 2019, "month": 10, "day": 4, "type": "payment", "amount": 5948 },
{ "year": 2019, "month": 10, "day": 7, "type": "withdrawal", "amount": 4400 },
{ "year": 2019, "month": 10, "day": 8, "type": "payment", "amount": 9677 },
{ "year": 2019, "month": 10, "day": 9, "type": "payment", "amount": 3912 },
{ "year": 2019, "month": 10, "day": 9, "type": "replenishment", "amount": 3870 },
{ "year": 2019, "month": 10, "day": 9, "type": "payment", "amount": 6949 },
{ "year": 2019, "month": 10, "day": 10, "type": "withdrawal", "amount": 3400 },
{ "year": 2019, "month": 10, "day": 10, "type": "replenishment", "amount": 7471 },
{ "year": 2019, "month": 10, "day": 10, "type": "payment", "amount": 5962 },
{ "year": 2019, "month": 10, "day": 10, "type": "payment", "amount": 4990 },
{ "year": 2019, "month": 10, "day": 10, "type": "withdrawal", "amount": 3000 },
{ "year": 2019, "month": 10, "day": 11, "type": "withdrawal", "amount": 200 },
{ "year": 2019, "month": 10, "day": 12, "type": "withdrawal", "amount": 1300 },
{ "year": 2019, "month": 10, "day": 13, "type": "payment", "amount": 986 },
{ "year": 2019, "month": 10, "day": 14, "type": "replenishment", "amount": 4225 },
{ "year": 2019, "month": 10, "day": 15, "type": "withdrawal", "amount": 900 },
{ "year": 2019, "month": 10, "day": 17, "type": "payment", "amount": 864 },
{ "year": 2019, "month": 10, "day": 17, "type": "withdrawal", "amount": 1000 },
{ "year": 2019, "month": 10, "day": 18, "type": "payment", "amount": 801 },
{ "year": 2019, "month": 10, "day": 19, "type": "withdrawal", "amount": 300 },
{ "year": 2019, "month": 10, "day": 20, "type": "payment", "amount": 530 },
{ "year": 2019, "month": 11, "day": 1, "type": "replenishment", "amount": 80285 },
{ "year": 2019, "month": 11, "day": 3, "type": "payment", "amount": 38155 },
{ "year": 2019, "month": 11, "day": 6, "type": "payment", "amount": 10260 },
{ "year": 2019, "month": 11, "day": 9, "type": "payment", "amount": 11013 },
{ "year": 2019, "month": 11, "day": 10, "type": "payment", "amount": 1232 },
{ "year": 2019, "month": 11, "day": 12, "type": "withdrawal", "amount": 5100 },
{ "year": 2019, "month": 11, "day": 12, "type": "payment", "amount": 1192 },
{ "year": 2019, "month": 11, "day": 13, "type": "withdrawal", "amount": 4500 },
{ "year": 2019, "month": 11, "day": 14, "type": "replenishment", "amount": 4304 },
{ "year": 2019, "month": 11, "day": 15, "type": "withdrawal", "amount": 700 },
{ "year": 2019, "month": 11, "day": 15, "type": "replenishment", "amount": 15857 },
{ "year": 2019, "month": 11, "day": 17, "type": "payment", "amount": 9134 },
{ "year": 2019, "month": 11, "day": 19, "type": "payment", "amount": 8090 },
{ "year": 2019, "month": 11, "day": 20, "type": "payment", "amount": 2117 },
{ "year": 2019, "month": 11, "day": 20, "type": "withdrawal", "amount": 2700 },
{ "year": 2019, "month": 11, "day": 21, "type": "withdrawal", "amount": 2200 },
{ "year": 2019, "month": 11, "day": 21, "type": "payment", "amount": 258 },
{ "year": 2019, "month": 11, "day": 21, "type": "withdrawal", "amount": 1200 },
{ "year": 2019, "month": 11, "day": 21, "type": "payment", "amount": 1966 },
{ "year": 2019, "month": 11, "day": 21, "type": "withdrawal", "amount": 200 },
{ "year": 2019, "month": 11, "day": 21, "type": "payment", "amount": 493 },
{ "year": 2019, "month": 11, "day": 21, "type": "payment", "amount": 396 },
{ "year": 2019, "month": 11, "day": 21, "type": "withdrawal", "amount": 200 },
{ "year": 2019, "month": 11, "day": 21, "type": "payment", "amount": 134 },
{ "year": 2019, "month": 11, "day": 22, "type": "replenishment", "amount": 4815 },
{ "year": 2019, "month": 11, "day": 22, "type": "withdrawal", "amount": 500 },
{ "year": 2019, "month": 11, "day": 23, "type": "payment", "amount": 1793 },
{ "year": 2019, "month": 12, "day": 1, "type": "replenishment", "amount": 93524 },
{ "year": 2019, "month": 12, "day": 2, "type": "payment", "amount": 44289 },
{ "year": 2019, "month": 12, "day": 2, "type": "payment", "amount": 7724 },
{ "year": 2019, "month": 12, "day": 4, "type": "payment", "amount": 9420 },
{ "year": 2019, "month": 12, "day": 4, "type": "withdrawal", "amount": 3200 },
{ "year": 2019, "month": 12, "day": 4, "type": "payment", "amount": 651 },
{ "year": 2019, "month": 12, "day": 6, "type": "payment", "amount": 9259 },
{ "year": 2019, "month": 12, "day": 6, "type": "withdrawal", "amount": 5700 },
{ "year": 2019, "month": 12, "day": 7, "type": "payment", "amount": 1298 },
{ "year": 2019, "month": 12, "day": 9, "type": "payment", "amount": 3108 },
{ "year": 2019, "month": 12, "day": 11, "type": "withdrawal", "amount": 4300 },
{ "year": 2019, "month": 12, "day": 13, "type": "withdrawal", "amount": 200 },
{ "year": 2019, "month": 12, "day": 13, "type": "replenishment", "amount": 9096 },
{ "year": 2019, "month": 12, "day": 14, "type": "payment", "amount": 7205 },
{ "year": 2019, "month": 12, "day": 16, "type": "payment", "amount": 658 },
{ "year": 2019, "month": 12, "day": 17, "type": "replenishment", "amount": 9654 }
]
First, for the task_1, I get an object that contains values by the key "month":
var arr1 = ops.map(function(item){
return item.month
})
Then I find the sum of the unique values in the resulting array:
quantity var = {};
for (var i = 0; i <arr1.length; i++){
quantity [arr1[i]] = 1 + (quantity [arr1[i]]|/ 0);
}
and I get the counts object in the following form:
counts
{1: 27, 2: 11, 3: 23, 4: 20, 5: 17, 6: 21, 7: 11, 8: 24, 9: 19, 10: 26, 11: 27, 12: 16}
After that, I sort to find the 3 maximum values:
function findMax 3(obj){
var res = [-1,-1,-1];
for (let key in obj){
res[3] = obj[key];
res.sort(function(a,b){return b-a});
}
res.pop();
return res;
}
console.log(findMax3(counts));
In the console I get the following:
[27, 27, 26]
but at the same time, I no longer know the index of the months to which these values relate
Thank you for your answers!
To solve these problems here is the hint "GroupBy using reduce"
As for task1
function task_1(arr) {
// Dictionary of Month to Object.
const groupedByMonth = arr.reduce(function (acc, currentValue) {
let groupKey = currentValue.month;
if (!acc[groupKey]) {
acc[groupKey] = {
year: currentValue.year,
month: currentValue.month,
opsCount: 0
};
}
acc[groupKey].opsCount += 1; // ++
return acc;
}, {});
// Sort by opsCount
function opsSort(a, b) { return b.opsCount - a.opsCount };
return Object
.values(groupedByMonth) // Array of Values
.sort(opsSort)
.slice(0, 3) // Top 3
}
Once you understand how task 1 is solved, task 2 becomes a bit simpler
Solution for Task 2
function getEndOfMonth(year, month) {
const date = new Date(year, month, 0);
let monthStr = "";
if (month < 10) {
monthStr += "0";
}
monthStr += month;
return year + "-" + monthStr + "-" + date.getDate();
}
function getRank(rate) {
if (rate < 0.15)
return 'Gold';
if (rate < 0.3)
return 'Gold';
return 'Bronze';
}
function task_2(arr) {
const groupedByMonth = arr.reduce(function (acc, currentValue) {
let groupKey = currentValue.month;
if (!acc[groupKey]) {
acc[groupKey] = {
date: getEndOfMonth(currentValue.year, currentValue.month),
monthWithrawal: 0,
totalDebits: 0,
totalDeposits: 0
};
}
// Based on type calculate value.
if (currentValue.type === "replenishment") {
acc[groupKey].totalDeposits += currentValue.amount;
} else if (currentValue.type === "payment") {
acc[groupKey].totalDebits += currentValue.amount;
} else if (currentValue.type === "withdrawal") {
acc[groupKey].monthWithrawal += currentValue.amount;
}
return acc;
}, {});
return Object
.values(groupedByMonth) // Array of Values
.map(function (ele) {
const withdrawalRate = ele.monthWithrawal / ele.totalDeposits;
return {
date: ele.date,
monthBalance: ele.totalDeposits - ele.totalDebits - ele.monthWithrawal,
monthWithrawal: ele.monthWithrawal,
withdrawalRate,
rank: getRank(withdrawalRate)
};
});
}
if you have solved task 2, task 3 is just adding reduce/map to task2's solution.
function task_3(arr) {
// Assuming that task_2 function is defined.
const task2 = task_2(arr);
// Can be Solved using reduce.
return task2
.map(function (currentValue, index, array) {
const tmp = currentValue;
tmp.totalBalance = tmp.monthBalance;
if (index > 0) { // Not the first element.
tmp.totalBalance += array[index - 1].totalBalance;
}
return tmp;
})
}
Task 1
const task_1 = (arr, top = 3) => {
const ops = arr.reduce((acc, {year, month}) => {
const accByMonth = acc.find((obj) => (obj.month === month));
if (accByMonth) {
accByMonth.opsCount +=1;
} else {
acc.push({ year, month, opsCount: 1 })
}
return acc;
}, []);
const sortedOps = ops.sort(
(obj1, obj2) => (obj2.opsCount - obj1.opsCount)
);
return sortedOps.slice(0, top);
}
console.log(task_1(data));
//[
// { year: 2019, month: 1, opsCount: 27 },
// { year: 2019, month: 11, opsCount: 27 },
// { year: 2019, month: 10, opsCount: 26 }
//]
Task 2
const getTotalByType = (arr, type) => arr
.filter((obj) => obj.type === type)
.reduce((sum, { amount }) => sum + amount, 0);
const getRank = (ratio) =>{
const ranks = [[0.15, 'Gold'], [0.3, 'Silver'], [Infinity, 'Bronze']]
return ranks.find(([ rankRatio ]) => ratio < rankRatio)[1];
}
const task_2 = (year, month, arr) => {
const filteredData = arr.filter((obj) => (obj.year === year) && (obj.month === month));
const maxDay = Math.max(...filteredData.map(({ day }) => day));
const date = new Date(year, month - 1, maxDay).toISOString().split('T')[0];
const monthReplenishment = getTotalByType(filteredData, 'replenishment');
const monthPayment = getTotalByType(filteredData, 'payment');
const monthWithdrawal = getTotalByType(filteredData, 'withdrawal');
const monthBalance = monthReplenishment - monthPayment - monthWithdrawal;
const withdrawalRate = parseFloat((monthWithdrawal / monthReplenishment).toFixed(4));
const rank = getRank(withdrawalRate);
return {
date,
monthBalance,
monthWithdrawal,
withdrawalRate,
rank,
}
};
console.log(task_2(2019, 7, data));
//{
// date: '2019-07-13',
// monthBalance: -2244,
// monthWithdrawal: 2100,
// withdrawalRate: 0.0406,
// rank: 'Gold'
//}
Task 3
const getPeriods = (arr) => arr.
reduce((acc, {year, month}) => {
const isPeriodInAcc = acc.some(
(obj) => (obj.month === month) && (obj.year === year)
);
if (!isPeriodInAcc) {
acc.push({ year, month })
}
return acc;
}, [])
const task_3 = (arr, initialBalance = 0) => {
const periods = getPeriods(arr);
let totalBalance = initialBalance;
return periods.map(({ year, month }) => {
const opsByPeriod = task_2(year, month, arr);
totalBalance += opsByPeriod.monthBalance;
return {...opsByPeriod, totalBalance}
});
}
console.log(task_3(data));
//[
// {
// date: '2019-01-22',
// monthBalance: 3829,
// monthWithdrawal: 33800,
// withdrawalRate: 0.3134,
// rank: 'Bronze',
// totalBalance: 3829
// },
// ...
// {...},
//]

Disable JSON auto merging data with same ID

I have a simple ajax call to PHP Select request like this :
$.ajax({
type: "POST",
url: "/renforts/_getIntervenantManager",
data: {
IDMission : IDMission,
IDManager : IDManager
},
dataType : 'json',
global: false,
success: function(respond)
{
console.log(respond);
}
});
and my PHP file look like :
$CUIDManager = $_POST['IDManager'];
$IDMission = $_POST['IDMission'];
$pdo_sql_renforts = DB_renforts();
$sql= "SELECT [IDIntervenant], [week], [hours], [year] FROM ....";
$requete = $pdo_sql_renforts->prepare($sql);
$requete->execute(array($IDMission, $IDMission,$CUIDManager));
$tab = $requete->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($tab);
So far so good here, because I get my respond.
My problem now is that my sql select return something like :
IDIntervenant
week
hours
year
1
22
16
2021
1
23
16
2021
1
24
16
2021
2
22
16
2021
3
25
16
2021
But the JSON respond that I have is merging the line with same ID and create stranges arrays in the first appearance of an ID like this :
0 : {
"CUIDIntervenant": "1",
"week": [
[
"22",
"23"
],
"24"
],
"hours": [
[
"16",
"16"
],
"16"
],
"year": [
[
"2021",
"2021"
],
"2021"
],
}
1 : {
"CUIDIntervenant": "1",
"week": "23",
"hours": "16",
"year": "2021"
}
2 : {
"CUIDIntervenant": "1",
"week": "24",
"hours": "16",
"year": "2021"
}
3 : {
"CUIDIntervenant": "2",
"week": "22",
"hours": "16",
"year": "2021"
}
4 : {
"CUIDIntervenant": "3",
"week": "25",
"hours": "16",
"year": "2021"
}
And what I want is :
0 : {
"CUIDIntervenant": "1",
"week": "22",
"hours": "16",
"year": "2021"
}
1 : {
"CUIDIntervenant": "1",
"week": "23",
"hours": "16",
"year": "2021"
}
2 : {
"CUIDIntervenant": "1",
"week": "24",
"hours": "16",
"year": "2021"
}
3 : {
"CUIDIntervenant": "2",
"week": "22",
"hours": "16",
"year": "2021"
}
4 : {
"CUIDIntervenant": "3",
"week": "25",
"hours": "16",
"year": "2021"
}
The json is correct, something is happening inside jquery that messing it up. Try receive it as text and convert it manually:
$.ajax({
type: "POST",
url: "/renforts/_getIntervenantManager",
data: {
mission: IDMission,
IDManager: IDManager
},
dataType: 'text',
global: false,
success: function(respond) {
console.log("original response");
console.log(respond);
console.log("JSON");
console.log(JSON.parse(respond));
}
});

How to use Array.prototype.filter to selectively filter Json data while renaming object's properties in the resulting array?

I have a Json that looks like this
{
"score": "1200.65",
"num_games": "160",
"wins": "110",
"year": "2013"
},
{
"score": "705.23",
"num_games": "34",
"wins": "21",
"year": "2014"
},
{
"score": "467.12",
"num_games": "77",
"wins": "30",
"year": "2015"
},
I'd like to create an array of objects (containing x and y) that can be filtered by a range of years (for example years between 2014 and 2015) for the x property, and a specific property's value as the y (for example "score").
For example, if I filter by range of years 2014-2015 and by property "score", the resulting array should be:
[{x:'2014', y: 705.23}, {x:'2015', y: 467.12}]
Another example, if I filter by range of years 2014-2015 and by property "num_games", the resulting array should be:
[{x:'2014', y: 34}, {x:'2015', y: 77}]
How should i go about this? Is Array.prototype.filter the right tool for this?
Filter the array using Array#filter
Convert the elements of the array to a type of your choosing using Array#map
var data = [{"score": "1200.65", "num_games": "160", "wins": "110", "year": "2013" }, { "score": "705.23", "num_games": "34", "wins": "21", "year": "2014" }, { "score": "467.12", "num_games": "77", "wins": "30", "year": "2015" }];
function getFilteredData(data, start, end) {
return data.filter(function(item) {
return +start <= +item.year && +item.year <= +end;
}).map(function(item) {
return {
x: item.year,
y: item.score
};
});
}
console.log(getFilteredData(data, 2014, 2017));
If your dates are within reasonable boundaries you don't have to convert the year to a number but any 3- or 5+ digit years will not filter properly, unless you convert the years to numbers.
If you want a more abstract version of the function you could do:
var data = [{"score": "1200.65", "num_games": "160", "wins": "110", "year": "2013" }, { "score": "705.23", "num_games": "34", "wins": "21", "year": "2014" }, { "score": "467.12", "num_games": "77", "wins": "30", "year": "2015" }];
function getFilteredData(data, filterOptions, mapOptions) {
return data.filter(function(item) {
return Object.keys(filterOptions).every(function(key) {
var option = filterOptions[key];
if (+option.min <= +item[key] && +item[key] <= +option.max) return true;
});
}).map(function(item) {
return Object.keys(mapOptions).reduce(function(result, key) {
var option = mapOptions[key];
result[key] = item[option];
return result;
}, {});
});
}
function registerFilter(filterOptions, mapOptions) {
return function(data) {
return getFilteredData(data, filterOptions, mapOptions);
};
}
var customFilter = registerFilter(
{ year: { min: 2014, max: 2015 },
{ x: "year", y: "score" }
);
console.log(customFilter(data));
You could do both operations together using a for loop or Array#reduce. Which makes the code faster but less maintainable.
var data = [{"score": "1200.65", "num_games": "160", "wins": "110", "year": "2013" }, { "score": "705.23", "num_games": "34", "wins": "21", "year": "2014" }, { "score": "467.12", "num_games": "77", "wins": "30", "year": "2015" }];
function getFilteredData(data, start, end) {
return data.reduce(function(result, item) {
if (+start <= +item.year && +item.year <= +end) result.push({
x: item.year,
y: item.score
});
return result;
}, []);
}
console.log(getFilteredData(data, 2014, 2017));
Filter , Map , Object Destructing can do the job :
const y = [{
"score": "1200.65",
"num_games": "160",
"wins": "110",
"year": "2013"
},
{
"score": "705.23",
"num_games": "34",
"wins": "21",
"year": "2014"
},
{
"score": "467.12",
"num_games": "77",
"wins": "30",
"year": "2015"
}
];
const res = y.filter(o => o.year == 2014).map(({
year: x,
score: y
}) => ({
x,
y
}))
console.log(res)
You could filter and map the wanted values.
function getParts(array, [min, max], key) {
return array
.filter(({ year }) => +min <= year && year <= +max)
.map(({ year: x, [key]: y }) => ({ x, y }));
}
var data = [{ score: "1200.65", num_games: "160", wins: "110", year: "2013" }, { score: "705.23", num_games: "34", wins: "21", year: "2014" }, { score: "467.12", num_games: "77", wins: "30", year: "2015" }];
console.log(getParts(data, [2014, 2015], 'score'));
console.log(getParts(data, [2014, 2015], 'num_games'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use .filter to get the objects within your required range, and then use .map to create the objects from the filtered list.
See example below:
const arr = [{
"score": "1200.65",
"num_games": "160",
"wins": "110",
"year": "2013"
},
{
"score": "705.23",
"num_games": "34",
"wins": "21",
"year": "2014"
},
{
"score": "467.12",
"num_games": "77",
"wins": "30",
"year": "2015"
}];
const get_items = (arr, [sY, eY], prop) =>
arr
.filter(({year}) => +sY <= year && year <= +eY)
.map(({year:x, ...rest}) => ({x, y: rest[prop]}));
console.log(get_items(arr, ["2014", "2015"], "score"));
First filter the array by dates, then map the filtered items to your required format. You can use destructuring to make the code shorter:
const data = [{
"score": "1200.65",
"num_games": "160",
"wins": "110",
"year": "2013"
}, {
"score": "705.23",
"num_games": "34",
"wins": "21",
"year": "2014"
}, {
"score": "467.12",
"num_games": "77",
"wins": "30",
"year": "2015"
}];
const filterBy = (data, [min, max], prop) => data
.filter(({ year }) => year >= min && year <= max)
.map(({ year: x, [prop]: y }) => ({ x, y }));
console.log(filterBy(data, [2013, 2014], 'score'));
console.log(filterBy(data, [2013, 2013], 'wins'));

Group values with the same key in an array of objects

To display data in highcharts.js I need to turn the following data:
"personas": [
{
"category":"Persona1",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.5,
"weekaverage":1.33333333333333,
"monthaverage":1.53571428571429
},
{
"category":"Persona2",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.146477031224456,
"weekaverage":0.194758246723904,
"monthaverage":0.601273296708939
},
{
"category":"Persona3",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":1.25559947299078,
"weekaverage":1.43618513323983,
"monthaverage":0.998426393184655
},
{
"category":"Persona4",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.799332962757087,
"weekaverage":0.923262727610554,
"monthaverage":0.769477297163179
},
{
"category":"Persona5",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.669041769041769,
"weekaverage":0.67394482002558,
"monthaverage":0.670944920469891
},
{
"category":"Persona6",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.656381486676017,
"weekaverage":0.722973507315144,
"monthaverage":0.69689774371321
},
{
"category":"Persona7",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.540495407737267,
"weekaverage":0.576413277444205,
"monthaverage":0.693495281755596
}
]
Into this format:
[
{
name: 'dayaverage',
data: [0.5, 0.146477031224456, 1.25559947299078, 0.799332962757087, 0.669041769041769, 0.656381486676017, 0.540495407737267]
},
{
name: 'weekaverage',
data: [1.33333333333333, 0.194758246723904, 1.43618513323983, 0.923262727610554, 0.67394482002558, 0.722973507315144, 0.576413277444205]
}, {
name: 'monthaverage',
data: [1.53571428571429, 0.601273296708939, 0.998426393184655, 0.769477297163179, 0.670944920469891, 0.69689774371321, 0.693495281755596]
}
].
All I'm doing is grouping the dayaverage, weekaverage and monthaverage values into an array and specifying what they are with a name key-value pair.
I'm having trouble writing this because the parent function is going to call with a list of criteria (for the above example it was : criteria = ['dayaverage', 'weekaverage', 'monthaverage'];) and that could change.
Any help appreciated, thanks
You could use an array for the wanted properties and build an array with the data upon.
function getGrouped(array, groups) {
var grouped = groups.map(function (a) {
return { name: a, data: [] };
});
array.personas.forEach(function (a) {
groups.forEach(function (k, i) {
grouped[i].data.push(a[k]);
});
});
return grouped;
}
var data = { personas: [{ category: "Persona1", month: 6, week: 24, day: 18, dayaverage: 0.5, weekaverage: 1.33333333333333, monthaverage: 1.53571428571429 }, { category: "Persona2", month: 6, week: 24, day: 18, dayaverage: 0.146477031224456, weekaverage: 0.194758246723904, monthaverage: 0.601273296708939 }, { category: "Persona3", month: 6, week: 24, day: 18, dayaverage: 1.25559947299078, weekaverage: 1.43618513323983, monthaverage: 0.998426393184655 }, { category: "Persona4", month: 6, week: 24, day: 18, dayaverage: 0.799332962757087, weekaverage: 0.923262727610554, monthaverage: 0.769477297163179 }, { category: "Persona5", month: 6, week: 24, day: 18, dayaverage: 0.669041769041769, weekaverage: 0.67394482002558, monthaverage: 0.670944920469891 }, { category: "Persona6", month: 6, week: 24, day: 18, dayaverage: 0.656381486676017, weekaverage: 0.722973507315144, monthaverage: 0.69689774371321 }, { category: "Persona7", month: 6, week: 24, day: 18, dayaverage: 0.540495407737267, weekaverage: 0.576413277444205, monthaverage: 0.693495281755596 }] };
console.log(getGrouped(data, ['day', 'dayaverage', 'weekaverage', 'monthaverage']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this using .map() along with .reduce() like so:
Also, to use dynamic properties, you can use bracket syntax ([]) for accessing properties on an object. Here, you can .map() your criteria list into the desired structure, and calculate the data using .reduce().
EDIT - Fixed resulting data structure to accurately output desired results
var personas = [{
"category": "Persona1",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.5,
"weekaverage": 1.33333333333333,
"monthaverage": 1.53571428571429
},
{
"category": "Persona2",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.146477031224456,
"weekaverage": 0.194758246723904,
"monthaverage": 0.601273296708939
},
{
"category": "Persona3",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 1.25559947299078,
"weekaverage": 1.43618513323983,
"monthaverage": 0.998426393184655
},
{
"category": "Persona4",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.799332962757087,
"weekaverage": 0.923262727610554,
"monthaverage": 0.769477297163179
},
{
"category": "Persona5",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.669041769041769,
"weekaverage": 0.67394482002558,
"monthaverage": 0.670944920469891
},
{
"category": "Persona6",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.656381486676017,
"weekaverage": 0.722973507315144,
"monthaverage": 0.69689774371321
},
{
"category": "Persona7",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.540495407737267,
"weekaverage": 0.576413277444205,
"monthaverage": 0.693495281755596
}
];
var criteria = ['dayaverage', 'weekaverage', 'monthaverage'];
function getMerged(objArr, criteria) {
var dataMap = objArr.reduce(function (result, current) {
criteria.forEach(function (elem) {
if (result[elem] != undefined) {
result[elem].push(current[elem]);
}
else {
result[elem] = [current[elem]];
}
});
return result;
}, {});
return criteria.map(function (elem) {
return {
name: elem,
data: dataMap[elem]
};
});
}
console.log(getMerged(personas, criteria));
One of the ways how to solve it, using Array#forEach.
var json = {personas:[{category:"Persona1",month:"6",week:"24",day:"18",dayaverage:.5,weekaverage:1.33333333333333,monthaverage:1.53571428571429},{category:"Persona2",month:"6",week:"24",day:"18",dayaverage:.146477031224456,weekaverage:.194758246723904,monthaverage:.601273296708939},{category:"Persona3",month:"6",week:"24",day:"18",dayaverage:1.25559947299078,weekaverage:1.43618513323983,monthaverage:.998426393184655},{category:"Persona4",month:"6",week:"24",day:"18",dayaverage:.799332962757087,weekaverage:.923262727610554,monthaverage:.769477297163179},{category:"Persona5",month:"6",week:"24",day:"18",dayaverage:.669041769041769,weekaverage:.67394482002558,monthaverage:.670944920469891},{category:"Persona6",month:"6",week:"24",day:"18",dayaverage:.656381486676017,weekaverage:.722973507315144,monthaverage:.69689774371321},{category:"Persona7",month:"6",week:"24",day:"18",dayaverage:.540495407737267,weekaverage:.576413277444205,monthaverage:.693495281755596}]},
criteria = ['dayaverage', 'weekaverage', 'monthaverage'],
arr = criteria.reduce(function(s,a){
s.push({name: a, data: []});
return s;
}, []);
arr.forEach(function(v) {
json.personas.forEach(function(c) {
v.data.push(c[v.name]);
})
})
console.log(arr);
try this:
var criteria = ['dayaverage', 'weekaverage', 'monthaverage']; //your dynamic criteria
var arr= []; //the filtered array you want
criteria.forEach(function(criterium){
// for each criterium you create a new object that you add to arr
arr.push({
name: criterium,
data: []
});
// then you populate the data field of the newly created field by browsing your big array "personas" that you need to parse before btw
personas.forEach(function (persona) {
arr[arr.length-1].data.push(persona[criterium]);
});
});
You can map the keys to an array of objects and map each of the objects' values by the current key in the mapping process.
var data = getData();
var modified = modify(data, 'personas', ['dayaverage', 'weekaverage', 'monthaverage']);
console.log(JSON.stringify(modified, null, 2));
function modify(data, root, keep) {
data = data[root] != null ? data[root] : data;
var keys = Object.keys(data[0]);
if (keep != null && keep.length > 0)
keys = keys.filter(key => keep.indexOf(key) > -1);
return keys.map(key => {
return {
name: key,
data: data.map(item => item[key])
}
});
}
function getData() {
return {
"personas": [{
"category": "Persona1",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.5,
"weekaverage": 1.33333333333333,
"monthaverage": 1.53571428571429
}, {
"category": "Persona2",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.146477031224456,
"weekaverage": 0.194758246723904,
"monthaverage": 0.601273296708939
}, {
"category": "Persona3",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 1.25559947299078,
"weekaverage": 1.43618513323983,
"monthaverage": 0.998426393184655
}, {
"category": "Persona4",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.799332962757087,
"weekaverage": 0.923262727610554,
"monthaverage": 0.769477297163179
}, {
"category": "Persona5",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.669041769041769,
"weekaverage": 0.67394482002558,
"monthaverage": 0.670944920469891
}, {
"category": "Persona6",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.656381486676017,
"weekaverage": 0.722973507315144,
"monthaverage": 0.69689774371321
}, {
"category": "Persona7",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.540495407737267,
"weekaverage": 0.576413277444205,
"monthaverage": 0.693495281755596
}]
};
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

JSON iterating through objects and accessing data result to cannot read property of undefined

I'm parsing a json from a website and trying to get some data from it. However, it is giving me undefined values when iterating through a collection of objects. If it's a badly formatted json, unfortunately, I can't change it.
[
{
"startYear": 2014,
"startMonth": 6,
"startDay": 31,
"endYear": 2014,
"endMonth": 7,
"endDay": 29,
"selectedDate": "2014_7_8",
"departureStation": "Manila",
"arrivalStation": "Boracay (Caticlan)",
"departureStationCode": "(MNL)",
"arrivalStationCode": "(MPH)",
"departureLabel": "DEPARTURE",
"arrivalLabel": "RETURN",
"dateMarketHash": {
"date_0_2014_6_31": {
"containerId": "date_0_2014_6_31",
"fromLabel": "From",
"currency": "PHP",
"price": null,
"formattedDate": "Thu, Jul 31, 2014",
"year": "2014",
"month": "6",
"day": "31",
"points": null,
"pointsSuffix": "",
"pointsLabelAppend": ""
},
"date_0_2014_7_1": {
"containerId": "date_0_2014_7_1",
"fromLabel": "From",
"currency": "PHP",
"price": 1929,
"formattedDate": "Fri, Aug 01, 2014",
"year": "2014",
"month": "7",
"day": "1",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
}
}
},
{
"startYear": 2014,
"startMonth": 7,
"startDay": 24,
"endYear": 2014,
"endMonth": 8,
"endDay": 23,
"selectedDate": "2014_8_8",
"departureStation": "Boracay (Caticlan)",
"arrivalStation": "Manila",
"departureStationCode": "(MPH)",
"arrivalStationCode": "(MNL)",
"departureLabel": "DEPARTURE",
"arrivalLabel": "RETURN",
"dateMarketHash": {
"date_1_2014_7_24": {
"containerId": "date_1_2014_7_24",
"fromLabel": "From",
"currency": "PHP",
"price": 3079,
"formattedDate": "Sun, Aug 24, 2014",
"year": "2014",
"month": "7",
"day": "24",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
},
"date_1_2014_7_25": {
"containerId": "date_1_2014_7_25",
"fromLabel": "From",
"currency": "PHP",
"price": 3079,
"formattedDate": "Mon, Aug 25, 2014",
"year": "2014",
"month": "7",
"day": "25",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
}
}
}
]
my code:
// Printing the value of 'day' from each 'dateMarketHash'
for (i = 0; i<json.length; i++)
{
var current = json[i].dateMarketHash;
for(var key in current){
if (current.hasOwnProperty(key)) {
document.write(current.key.day); // Cannot read property 'day' of undefined
}
}
}
No, it is the fact that you are reading "key" and not the variable. You need to use bracket notation, not dot notation.
document.write(current[key].day);
And you should not be using document.write.

Categories