How to show subtotal in vue app from firebase rtdb - javascript

I'm trying to fix this method in my vue app. It will take an array of objects that will contain the price of a selled item and needs to return the total calculation of all elements. The problem is that it will be wrong and it's not correct, into the db and console log I see the correct values, do I need to fix something in the code?
I'm saving the value that is taken from a v-model field correctly in firebase, probably I don't need the for loop?
showSubtotalSelled(items){
let sum = 0
for(let i = 0; i < items.length; i++){
console.log(i)
//if( items[i].sellPrice === items[i].selledItemsValue ){
// let parsed = items[i].sellPrice.replace(',', '.')
// sum = ( parseFloat(sum) + parseFloat(parsed) ).toFixed(2)
//} else {
let parsed = items[i].sellPrice.replace(',', '.')
console.log(parsed)
sum = ( parseFloat(sum) + parseFloat(parsed) * items[i].pz ).toFixed(2)
//}
}
if( sum === 0.00 ){
return '0,00'
} else {
return sum.replace('.', ',')
}
}
This is the firebase rtdb scheme I'm using for the items
-NJ_CNw4b8Yx1UZoNz_j
color: "GRIGIO"
id: 55
name: "TERRACES BULLDOG"
pz: "1"
sellPrice: "30,00"
size: "XL"
uid: "-NJ_CNw4b8Yx1UZoNz_j"
This is a sample of the document I load from rtdb. The calculation is 30€ more than the expected, I suppose there is something that is summed twice when the data are loaded and used to display the subtotal?
"articoliVenduti": [
null,
{
"color": "NERO",
"id": 1,
"name": "SALERNITANA ZUCCOTTO TEAM",
"pz": "1",
"sellPrice": "13",
"size": "UNICA"
},
{
"color": "GRANATA",
"id": 2,
"name": "SALERNITANA FELPA TECH",
"pz": "1",
"sellPrice": "80",
"size": "XL"
},
{
"color": "GRANATA",
"id": 3,
"name": "SALERNITANA TRAPUNTA",
"pz": "1",
"sellPrice": "55",
"size": "UNICA"
},
{
"color": "GRANATA",
"id": 4,
"name": "SALERNITANA MAGLIONE NATALIZIO",
"pz": "1",
"sellPrice": "45",
"size": "L"
},
{
"color": "MAZZOCCHI",
"id": 5,
"name": "SALERNITANA MAGLIA GARA THIRD 2022/2023",
"pz": "1",
"sellPrice": "95",
"size": "M"
},
{
"color": "BLU NAVY",
"id": 6,
"name": "LYLE SCOTT SOFTSHELL JACKET",
"pz": "1",
"sellPrice": "130",
"size": "L"
},
{
"color": "BLU NAVY",
"id": 7,
"name": "TERRACES CAPPELLO LANA",
"pz": "1",
"sellPrice": "30",
"size": "UNICA"
},
{
"color": "GIALLO",
"id": 8,
"name": "TERRACES CAPPELLO LANA",
"pz": "1",
"sellPrice": "30",
"size": "UNICA"
},
{
"color": "GRIGIO",
"id": 9,
"name": "TERRACES FELPA ZIP",
"pz": "1",
"sellPrice": "65",
"size": "XL"
},
{
"color": "BLU NAVY",
"id": 10,
"name": "TERRACES TESCHIO",
"pz": "1",
"sellPrice": "30",
"size": "XL"
},
{
"color": "GRIGIO",
"id": 11,
"name": "TERRACES BULLDOG",
"pz": "1",
"sellPrice": "30",
"size": "XL"
}
]
NB: To be more clear, data are saved correctly in rtdb, it's not there the problem, but I need to show on the vue front-end the exact calculation of all selled items that are loaded from rtdb.

You can use reduce function :
const arr = [{"color": "NERO", "id": 1, "name": "SALERNITANA ZUCCOTTO TEAM", "pz": "1", "sellPrice": "13", "size": "UNICA"}, {"color": "GRANATA", "id": 2, "name": "SALERNITANA FELPA TECH", "pz": "1", "sellPrice": "80", "size": "XL"}, {"color": "GRANATA", "id": 3, "name": "SALERNITANA TRAPUNTA", "pz": "1", "sellPrice": "55", "size": "UNICA"}, { "color": "GRANATA", "id": 4, "name": "SALERNITANA MAGLIONE NATALIZIO", "pz": "1", "sellPrice": "45", "size": "L"}, {"color": "MAZZOCCHI", "id": 5, "name": "SALERNITANA MAGLIA GARA THIRD 2022/2023", "pz": "1", "sellPrice": "95", "size": "M"}, {"color": "BLU NAVY", "id": 6, "name": "LYLE SCOTT SOFTSHELL JACKET", "pz": "1", "sellPrice": "130", "size": "L"}, {"color": "BLU NAVY", "id": 7, "name": "TERRACES CAPPELLO LANA", "pz": "1", "sellPrice": "30", "size": "UNICA"}, {"color": "GIALLO", "id": 8, "name": "TERRACES CAPPELLO LANA", "pz": "1", "sellPrice": "30", "size": "UNICA" }, {"color": "GRIGIO", "id": 9, "name": "TERRACES FELPA ZIP", "pz": "1", "sellPrice": "65", "size": "XL"}, { "color": "BLU NAVY", "id": 10, "name": "TERRACES TESCHIO", "pz": "1", "sellPrice": "30", "size": "XL"}, {"color": "GRIGIO", "id": 11, "name": "TERRACES BULLDOG", "pz": "1", "sellPrice": "30,85", "size": "XL" } ]
function showSubtotalSelled(items){
return items.reduce((a, b) => a + +b.sellPrice.replace(',', '.'), 0)
}
console.log(showSubtotalSelled(arr))

Related

How can I accurately return nested values from JSON for comparison and then complete the comparison?

I have asked a similar question before but I've not been able to expand on this and I haven't found the exact answer that would teach me how to do this. My JSON file will have the same structure in terms of the element names inside each nested object but the values will vary. In plain English, I want to start at the bottom of the file and return true if the following conditions occur and stop searching if true: AppStatus is one of these ["Approved", "Auto Approved", "Return"] and the nested keys of "Name": "Payments", "Value": "X" and "Name": "Term", "Value": "Y" have values that don't match. I'm providing a snippet of the JSON so you can see more easily. The AppStatus is 2nd level and the Name, Value are 3rd level. In this example, it should return true based on the 2nd set of data in DataElements.
{
"DecisionHistory": [
{
"Id": "273601",
"Number": "1",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [
{
"Id": "213922",
"Name": "Payments",
"Value": "72",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
},
{
"Id": "273601",
"Number": "2",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [
{
"Id": "213922",
"Name": "Payments",
"Value": "72",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
},
{
"Id": "273601",
"Number": "3",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [
{
"Id": "213922",
"Name": "Payments",
"Value": "75",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
}
]
}
I've tried using 2 ugly nested for loops without success. I would prefer not to use for loops if I don't have to. See below:
function main(jsonFile) {
const history = JSON.parse(jsonFile).DecisionHistory;
const appStatus = ["Approved", "Auto Approved", "Return"];
const termMonths = "TermMonths";
const numberOfPayments = "Number of Payments";
let termMonthsVal = 0;
let numberofPaymentsVal = 0;
for (let a = history.length - 1; a >= 0; a--) {
if (appStatus.includes(history[a].AppStatus)) {
var dataElementsA = history[a].DataElements;
for (let b = (dataElementsA.length) - 1; b >= 0; b--) {
if (dataElementsA[b].Name == termMonths) {
termMonthsVal = new Number((dataElementsA[b].Value));
break;
}
}
}
}
for (let a = history.length - 1; a >= 0; a--) {
if (appStatus.includes(history[a].AppStatus)) {
var dataElementsB = history[a].DataElements;
for (let b = (dataElementsB.length) - 1; b >= 0; b--) {
if (dataElementsB[b].Name == numberOfPayments) {
numberofPaymentsVal = new Number((dataElementsB[b].Value));
break;
}
}
}
}
return (termMonthsVal != numberofPaymentsVal);
}
let jsonFile = `{
"DecisionHistory": [{
"Id": "273601",
"Number": "1",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [{
"Id": "213922",
"Name": "Payments",
"Value": "72",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
},
{
"Id": "273601",
"Number": "2",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [{
"Id": "213922",
"Name": "Payments",
"Value": "72",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
},
{
"Id": "273601",
"Number": "3",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [{
"Id": "213922",
"Name": "Payments",
"Value": "75",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
}
]
}`;
console.log(main(jsonFile));
//var result = main("_inJson");
//module.exports = main;
As a side note, the jsonFile in the main function is read in from a resource folder in my VS Code and I'm exporting main to an app.js so I can run assertions against it. So the JSON posted here is actually in a separate file but this is the exact structure of the data.
What am I missing? .filter? .map? .reduce? Differnt breaks?
Here's a "one-liner" depending on how long you want your lines to be ;)
const x = {
"DecisionHistory": [
{
"AppStatus": "Approved",
"DataElements": [
{
"Name": "Payments",
"Value": "72",
},
{
"Name": "Decisioned By",
"Value": "ASDF",
},
{
"Name": "Term",
"Value": "75",
}
]
},
{
"AppStatus": "Approved",
"DataElements": [
{
"Name": "Payments",
"Value": "72",
},
{
"Name": "Decisioned By",
"Value": "ASDF",
},
{
"Name": "Term",
"Value": "75",
}
]
},
{
"AppStatus": "Approved",
"DataElements": [
{
"Name": "Payments",
"Value": "75",
},
{
"Name": "Decisioned By",
"Value": "ASDF",
},
{
"Name": "Term",
"Value": "75",
}
]
}
]
};
const bar = (f) =>
f.DecisionHistory.reverse().some((decision) => ["Approved", "Auto Approved", "Return"].includes(decision.AppStatus) && decision.DataElements.find((el) => el.Name === 'Payments')?.Value !== decision.DataElements.find((el) => el.Name === 'Term')?.Value);
console.log(bar(x));

Looping through objects and creating array then combining on id

I have a problem trying to build an array, then combine and output multiple objects depending on the id.
This is the problem (I hope it makes sense):
I am looping through multiple objects, then create an array depending on the value of the type of the object. I then take that array and build it into the object. Once that is done I need to run through all the objects and combine any that have the same id.
this is an example of how it would originally look:
[{
"id": "755",
"entities": ["14394551"],
"accountID": "755",
"accountName": "122060 Test7",
"amount": 43,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"type": "CustDep",
"salesOrderId": ["14394550"],
"memo": ["MAINGB588328"],
"exchangerate": 1
}, {
"id": "755",
"entities": ["14394553"],
"accountID": "755",
"accountName": "122060 Test7",
"amount": 28,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"type": "CustDep",
"salesOrderId": ["14394552"],
"memo": ["MAINGB588333"],
"exchangerate": 1
},{
"id": "758",
"entities": ["14439896"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 38,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "CustDep",
"salesOrderId": ["14439895"],
"memo": ["MICGB2454"],
"exchangerate": 1
}, {
"id": "758",
"entities": ["14434400"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 18,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "CustDep",
"salesOrderId": ["14434399"],
"memo": ["MICGB2453"],
"exchangerate": 1
}, {
"id": "758",
"entities": ["14430895"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 63,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "Dep",
"salesOrderId": ["14430894"],
"memo": ["MICGB2452"],
"exchangerate": 1
}, {
"id": "762",
"entities": ["14350538"],
"accountID": "762",
"accountName": "122100 TEST1",
"amount": 45,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "TEST1",
"webPaymentMethodID": "13",
"type": "CustDep",
"salesOrderId": ["14350537"],
"memo": ["MAINGB586991"],
"exchangerate": 1
}, {
"id": "760",
"entities": ["14350538"],
"accountID": "760",
"accountName": "122100 TEST2",
"amount": 49,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "TEST2",
"webPaymentMethodID": "13",
"type": "CustDep",
"salesOrderId": ["14321538"],
"memo": ["MAINGB452756"],
"exchangerate": 1
}]
then this is after the array has been created -> Depending on the type.
[
{
"id": "755",
"accountID": "755",
"accountName": "122060 Test7",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14394551"],
"amount": 43,
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"salesOrderId": ["14394550"],
"memo": ["MAINGB588328"]
}],
"deposit": []
}, {
"id": "755",
"accountID": "755",
"accountName": "122060 Test7",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14394553"],
"amount": 28,
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"salesOrderId": ["14394552"],
"memo": ["MAINGB588333"],
}],
"deposit": []
},{
"id": "758",
"entities": ["14439896"],
"accountID": "758",
"accountName": "122070 Test5",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14439896"],
"amount": 38,
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"salesOrderId": ["14439895"],
"memo": ["MICGB2454"]
}],
"deposit": []
}, {
"id": "758",
"accountID": "758",
"accountName": "122070 Test5",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit" : [{
"entities": ["14434400"],
"amount": 18,
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"salesOrderId": ["14434399"],
"memo": ["MICGB2453"]
}],
"deposit": []
}, {
"id": "758",
"accountID": "758",
"accountName": "122070 Test5",
"subsidiary": "2",
"currency": "1",
"type": "Dep",
"exchangerate": 1,
"customerDeposit": [],
"deposit": [{
"entities": ["14430895"],
"amount": 63,
"memo": ["MICGB2452"],
}]
}, {
"id": "762",
"accountID": "762",
"accountName": "122100 TEST1",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [
{
"entities": ["14350538"],
"amount": 45,
"webPaymentMethod": "TEST1",
"webPaymentMethodID": "13",
"salesOrderId": ["14350537"],
"memo": ["MAINGB586991"],
}
],
"deposit": []
}, {
"id": "760",
"accountID": "760",
"accountName": "122100 TEST2",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14350538"],
"amount": 49,
"webPaymentMethod": "TEST2",
"webPaymentMethodID": "13",
"salesOrderId": ["14321538"],
"memo": ["MAINGB452756"]
}],
"deposit": []
}]
then this would be what I want the final output to be - all the same id objects have the customerDeposit / deposit combined.
[
{
"id": "755",
"accountID": "755",
"accountName": "122060 Test7",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14394551"],
"amount": 43,
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"salesOrderId": ["14394550"],
"memo": ["MAINGB588328"]
}, {
"entities": ["14394553"],
"amount": 28,
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"salesOrderId": ["14394552"],
"memo": ["MAINGB588333"],
}],
"deposit": []
}, {
"id": "758",
"entities": ["14439896"],
"accountID": "758",
"accountName": "122070 Test5",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14439896"],
"amount": 38,
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"salesOrderId": ["14439895"],
"memo": ["MICGB2454"]
}, {
"entities": ["14434400"],
"amount": 18,
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"salesOrderId": ["14434399"],
"memo": ["MICGB2453"]
}],
"deposit": [{
"entities": ["14430895"],
"amount": 63,
"memo": ["MICGB2452"],
}]
}, {
"id": "762",
"accountID": "762",
"accountName": "122100 TEST1",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [
{
"entities": ["14350538"],
"amount": 45,
"webPaymentMethod": "TEST1",
"webPaymentMethodID": "13",
"salesOrderId": ["14350537"],
"memo": ["MAINGB586991"],
}
],
"deposit": []
}, {
"id": "760",
"accountID": "760",
"accountName": "122100 TEST2",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14350538"],
"amount": 49,
"webPaymentMethod": "TEST2",
"webPaymentMethodID": "13",
"salesOrderId": ["14321538"],
"memo": ["MAINGB452756"]
}],
"deposit": []
}]
This is my current code but it is not working as i want as it skips any ids that dont have more than one customerDeposit / deposit as it doesn't get into the if (objForId) statement.
function createDeposit(values) {
deposit = {
entities: values.entities,
amount: values.amount,
memo: values.memo,
};
return deposit;
}
function createCustomerDeposit(values) {
customerDeposit = {
entities: values.entities,
amount: values.amount,
memo: values.memo,
webPaymentMethod: values.webPaymentMethod,
webPaymentMethodID: values.webPaymentMethodID,
salesOrderId: values.salesOrderId,
};
return customerDeposit;
}
function run() {
const transferData = [{
"id": "755",
"entities": ["14394551"],
"accountID": "755",
"accountName": "122060 Test7",
"amount": 43,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"type": "CustDep",
"salesOrderId": ["14394550"],
"memo": ["MAINGB588328"],
"exchangerate": 1
}, {
"id": "755",
"entities": ["14394553"],
"accountID": "755",
"accountName": "122060 Test7",
"amount": 28,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"type": "CustDep",
"salesOrderId": ["14394552"],
"memo": ["MAINGB588333"],
"exchangerate": 1
},{
"id": "758",
"entities": ["14439896"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 38,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "CustDep",
"salesOrderId": ["14439895"],
"memo": ["MICGB2454"],
"exchangerate": 1
}, {
"id": "758",
"entities": ["14434400"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 18,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "CustDep",
"salesOrderId": ["14434399"],
"memo": ["MICGB2453"],
"exchangerate": 1
}, {
"id": "758",
"entities": ["14430895"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 63,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "Dep",
"salesOrderId": ["14430894"],
"memo": ["MICGB2452"],
"exchangerate": 1
}, {
"id": "762",
"entities": ["14350538"],
"accountID": "762",
"accountName": "122100 TEST1",
"amount": 45,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "TEST1",
"webPaymentMethodID": "13",
"type": "CustDep",
"salesOrderId": ["14350537"],
"memo": ["MAINGB586991"],
"exchangerate": 1
}, {
"id": "760",
"entities": ["14350538"],
"accountID": "760",
"accountName": "122100 TEST2",
"amount": 49,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "TEST2",
"webPaymentMethodID": "13",
"type": "CustDep",
"salesOrderId": ["14321538"],
"memo": ["MAINGB452756"],
"exchangerate": 1
}];
var customerDeposit = [];
var deposit = [];
var res = transferData.reduce(function (agg, obj) {
var objForId = agg.filter(function (idObj) {
return idObj.id === obj.id;
})[0];
if (objForId) {
if(obj.type === 'CustDep') {
objForId.customerDeposit.push(createCustomerDeposit(obj));
}
if(obj.type === 'Dep') {
objForId.deposit.push(createDeposit(obj));
}
} else {
agg.push({
id: obj.id,
accountID: obj.accountID,
accountName: obj.accountName,
subsidiary: obj.subsidiary,
currency: obj.currency,
exchangerate: obj.exchangerate,
customerDeposit,
deposit
});
customerDeposit = [];
deposit = [];
}
return agg;
}, []);
console.log(res);
}
run();
Any help would be really appreciated. Hopefully the question makes sense.
Thanks

How do I filter an object that is part of an array value?

Given the following data
[
{
"date": "2017-10-04",
"games": [
{
"notes": "Game was played",
"time": "2017-10-04T20:24:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "10",
"game_id": 1
},
{
"notes": "Game was played",
"time": "2017-10-04T12:35:30+00:00",
"sport": "lacrosse",
"owner": "steve",
"players": "6",
"game_id": 2
},
{
"notes": "Game was played",
"time": "2017-10-04T10:12:30+00:00",
"sport": "hockey",
"owner": "henry",
"players": "10",
"game_id": 4
}
]
},
{
"date": "2017-10-14",
"games": [
{
"notes": "Game was played",
"time": "2017-10-14T20:32:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "4",
"game_id": 3
},
{
"notes": "Game was played",
"time": "2017-10-14T20:34:30+00:00",
"sport": "soccer",
"owner": "john",
"players": "12",
"game_id": 5
}
]
}
]
how do I filter out the objects so that I only show the hockey games played on that date. Essentially I need the same array of objects back, but the object should only be shown if the games key = sport: hockey
I know I can only run the filter method on arrays, but I can't figure out how to loop over the object inside of the array and return the whole object again. Any help would be greatly appreciated.
Try:
const filtered = yourArray.map(item => ({...item, games: item.games.filter(game => game.sport === 'hockey')})
// When run, this produces:
[
{
"date": "2017-10-04",
"games": [
{
"game_id": 1,
"notes": "Game was played",
"owner": "steve",
"players": "10",
"sport": "hockey",
"time": "2017-10-04T20:24:30+00:00"
},
{
"game_id": 4,
"notes": "Game was played",
"owner": "henry",
"players": "10",
"sport": "hockey",
"time": "2017-10-04T10:12:30+00:00"
}
]
},
{
"date": "2017-10-14",
"games": [
{
"game_id": 3,
"notes": "Game was played",
"owner": "steve",
"players": "4",
"sport": "hockey",
"time": "2017-10-14T20:32:30+00:00"
}
]
}
]
Which I think is what you want.
I think the following code should do the trick:
var x=[
{
"date": "2017-10-04",
"games": [
{
"notes": "Game was played",
"time": "2017-10-04T20:24:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "10",
"game_id": 1
},
{
"notes": "Game was played",
"time": "2017-10-04T12:35:30+00:00",
"sport": "lacrosse",
"owner": "steve",
"players": "6",
"game_id": 2
},
{
"notes": "Game was played",
"time": "2017-10-04T10:12:30+00:00",
"sport": "hockey",
"owner": "henry",
"players": "10",
"game_id": 4
}
]
},
{
"date": "2017-10-14",
"games": [
{
"notes": "Game was played",
"time": "2017-10-14T20:32:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "4",
"game_id": 3
},
{
"notes": "Game was played",
"time": "2017-10-14T20:34:30+00:00",
"sport": "soccer",
"owner": "john",
"players": "12",
"game_id": 5
}
]
}]
function filterByDate (data, date){
return data.filter(function(entry){
return sameDay(new Date(entry.date), date)
})
}
function filterBySport(data, sport){
data.forEach(function(entry){
entry.games=entry.games.filter(function(entry2){
return entry2.sport===sport
})
})
return data
}
function sameDay(date1, date2){ //helper function to check for date equality
return date1.getFullYear()===date2.getFullYear() &&
date1.getMonth()===date2.getMonth() &&
date1.getDay()===date2.getDay()
}
function myFilter(data, date, sportType){ // the final function you have to call
return filterBySport(filterByDate(data, date), sportType)
}
console.log(myFilter(x, new Date("2017-10-04"), "hockey"))
Let's take an array :-
let students = [
{"Name": "Priya","marks": [50, 60, 70, 80, 90]},
{"Name": "Ankita","marks": [80, 90, 95]}
]
Now, I want to filter marks greater than or equal to 90, The code will look like this.
students.map((student) => {
return {...student,
marks: student.marks.filter((mark) => mark >= 90)
}
})
// Result will be [{"Name": "Priya", "marks": [90]}, {"Name": "Ankita","marks": [90,95]}]
Spread operator will expand student and then it will override the marks key with filtered marks value.
If you will not use spread operator,
students.map((student) => student.marks.filter((mark) => mark >= 90))
// Result will be [[90],[90]]
Then you will get only the filtered values and not the values on which you haven't applied the filter.

Loop outputs [object, object, object object] [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have been taking some online courses recently to try and understand the basics of programming, Gradually trying to increase the complexity of what I am learning. However I cannot seem to be able to control the output of my loop, I either get the last value or [object,object object,object object, object,object]
Any help would be greatly appreciated, I am sure this is quite simple but I have tried for in's for's and for each's and no luck so far.
{
"years": [
{
"id": "1",
"year": "2015",
"total": "55045",
"points": [
{
"id": "2",
"points": "600",
"total": "215",
"percent": "0.4"
},
{
"id": "3",
"points": "500-599",
"total": "5431",
"percent": "9.9"
},
{
"id": "4",
"points": "400-499",
"total": "14097",
"percent": "25.6"
},
{
"id": "5",
"points": "300-399",
"total": "14446",
"percent": "26.2"
},
{
"id": "6",
"points": "200-299",
"total": "9768",
"percent": "17.7"
},
{
"id": "7",
"points": "100-199",
"total": "6562",
"percent": "11.9"
},
{
"id": "8",
"points": " >100",
"total": "4526",
"percent": "8.2"
}
]
},
{
"id": "9",
"year": "2014",
"total": "54025",
"points": [
{
"id": "10",
"points": "600",
"total": "162",
"percent": "0.3"
},
{
"id": "11",
"points": "500-599",
"total": "5088",
"percent": "9.4"
},
{
"id": "12",
"points": "400-499",
"total": "13447",
"percent": "24.9"
},
{
"id": "13",
"points": "300-399",
"total": "14047",
"percent": "26"
},
{
"id": "14",
"points": "200-299",
"total": "9584",
"percent": "17.7"
},
{
"id": "15",
"points": "100-199",
"total": "6926",
"percent": "12.8"
},
{
"id": "16",
"points": " >100",
"total": "4771",
"percent": "8.8"
}
]
},
{
"id": "17",
"year": "2013",
"total": "52767",
"points": [
{
"id": "18",
"points": "600",
"total": "152",
"percent": "0.3"
},
{
"id": "19",
"points": "500-599",
"total": "4813",
"percent": "9.1"
},
{
"id": "20",
"points": "400-499",
"total": "12803",
"percent": "24.3"
},
{
"id": "21",
"points": "300-399",
"total": "13381",
"percent": "25.4"
},
{
"id": "22",
"points": "200-299",
"total": "9566",
"percent": "18.1"
},
{
"id": "23",
"points": "100-199",
"total": "6914",
"percent": "13.1"
},
{
"id": "24",
"points": " >100",
"total": "5138",
"percent": "9.7"
}
]
},
{
"id": "25",
"year": "2012",
"total": "52589",
"points": [
{
"id": "26",
"points": "600",
"total": "165",
"percent": "0.2"
},
{
"id": "27",
"points": "500-599",
"total": "5026",
"percent": "9.6"
},
{
"id": "28",
"points": "400-499",
"total": "12395",
"percent": "23.6"
},
{
"id": "29",
"points": "300-399",
"total": "13170",
"percent": "25"
},
{
"id": "30",
"points": "200-299",
"total": "9588",
"percent": "18.2"
},
{
"id": "31",
"points": "100-199",
"total": "6999",
"percent": "13.3"
},
{
"id": "32",
"points": " >100",
"total": "5276",
"percent": "10"
}
]
},
{
"id": "33",
"year": "2011",
"total": "54341",
"points": [
{
"id": "34",
"points": "600",
"total": "162",
"percent": "0.3"
},
{
"id": "35",
"points": "500-599",
"total": "4863",
"percent": "8.6"
},
{
"id": "36",
"points": "400-499",
"total": "12235",
"percent": "22.5"
},
{
"id": "37",
"points": "300-399",
"total": "13860",
"percent": "18.4"
},
{
"id": "38",
"points": "200-299",
"total": "9966",
"percent": "18.4"
},
{
"id": "39",
"points": "100-199",
"total": "7477",
"percent": "13.8"
},
{
"id": "40",
"points": " >100",
"total": "5928",
"percent": "10.9"
}
]
},
{
"id": "34",
"year": "2010",
"total": "54480",
"points": [
{
"id": "35",
"points": "600",
"total": "136",
"percent": "0.2"
},
{
"id": "36",
"points": "500-599",
"total": "4564",
"percent": "8.4"
},
{
"id": "37",
"points": "400-499",
"total": "11973",
"percent": "22"
},
{
"id": "38",
"points": "300-399",
"total": "13878",
"percent": "25.5"
},
{
"id": "39",
"points": "200-299",
"total": "10391",
"percent": "19.1"
},
{
"id": "40",
"points": "100-199",
"total": "7294",
"percent": "13.4"
},
{
"id": "41",
"points": " >100",
"total": "6244",
"percent": "11.5"
}
]
}
]
}
I am hoping someone can maybe help with controlling the output of the loop.
You haven't showed any code, but I can guess that your problem is something typical in JavaScript:
JavaScript closure inside loops – simple practical example
Check out neurosnap's answer.
http://coffeescript.org/#loops
In CoffeeScript it's even simpler:
for filename in list
do (filename) ->
fs.readFile filename, (err, contents) ->
compile filename, contents.toString()
Basically, you need a lambda/IIFE inside the for loop in JavaScript to loop to avoid your problem.

calculate the date diff in javascript from JSON array

I have a JSON object which returns a list of events with dates and times, I want to add a counter to the next event time, but i am not sure how to approach this?
Basically, my JSON is like:
[{"name": "BAKER-CROSSROADS", "country": "USA", "lon": "165.25", "yield": "21", "lat": "11.58", "depth": ".027", "date": "1946/07/24 21:35:00", "id": "1"}, {"name": "VENUS", "country": "USA", "lon": "-116.2", "yield": "10", "lat": "37.19", "depth": ".03", "date": "1958/02/22 01:00:00", "id": "10", "fill": "green"}, {"name": "HATCHIE", "country": "USA", "lon": "-116.03", "yield": "20", "lat": "37.058", "depth": ".061", "date": "1963/02/08 16:00:01", "id": "100", "fill": "green"}, {"name": "CLIMAX:Upshot-Knothole", "country": "USA", "lon": "-116.0183", "yield": "61", "lat": "37.0875", "depth": "-.41", "date": "1953/06/04 11:14:57", "id": "1000", "fill": "red"}, {"name": "BRAVO:Castle", "country": "USA", "lon": "165.274", "yield": "15000", "lat": "11.698", "depth": "0", "date": "1954/02/28 18:45:00", "id": "1001", "fill": "red"}, ....
so for each object:
{"name": "BAKER-CROSSROADS", "country": "USA", "lon": "165.25", "yield": "21", "lat": "11.58", "depth": ".027", "date": "1946/07/24 21:35:00", "id": "1"}
{"name": "VENUS", "country": "USA", "lon": "-116.2", "yield": "10", "lat": "37.19", "depth": ".03", "date": "1958/02/22 01:00:00", "id": "10", "fill": "green"}
...
here is the code that reads the json file:
this.loadNext = function () {
d3.json("./data/detonations.json", function(datum) {
for(var i = datum.length - 1; i >= 0; --i) {
var o = datum[i];
//console.log(o);
message = {
country: o.country
,date: o.date
,depth: o.depth
,lon: o.lon
,lat: o.lat
,type: o.type
,yield: o.yield
};
self.doSomething(message)
}
});
}
i would like to calculate the date/time difference, so in this case the difference of "1958/02/22 01:00:00" and "1946/07/24 21:35:00" and pass this to the message array?
To have this difference in millisecondes, you may use
var diff = (new Date(s2)).getTime() - (new Date(s1)).getTime();
That's because the format you have is directly parsable by the Date class.

Categories

Resources