I have a jsonDataArray that contains two nested arrays with objects. My goal is to calculate the number of "duty" parentIds based on the teams' "value" as they have a one-to-one match. For instance, Team A with a value of 500 will have duties such as Meetings and Lunch, while Team B will have duties like Time Cards, Parking, and Breakfast.
{
"jsonDataArray":[
{
"teams":[
{
"text":"Team A",
"id":1,
"value":500,
"parentId":333
},
{
"text":"Team B",
"id":2,
"value":600,
"parentId":444
}
],
"duty":[
{
"text":"Meetings",
"id":11,
"value":100,
"parentId":500
},
{
"text":"Lunch",
"id":12,
"value":101,
"parentId":500
},
{
"text":"Time Cards",
"id":13,
"value":102,
"parentId":600
},
{
"text":"Parking",
"id":14,
"value":103,
"parentId":600
},
{
"text":"Breakfast",
"id":15,
"value":104,
"parentId":600
}
]
}
]
}
I successfully retrieved the above JSON data using Vue (Axios). Below is my method.
I managed to count using reduce, but it only accounted for the first object in the array (teams) without any reference to duty. Is there a way to calculate by matching values and parentIds since they are in the same array...jsonDataArray.teams.value == jsonDataArray.duty.parentId ?
newJsonData() {
var dutyCount = this.jsonDataArray.flatMap((item) => item.teams);
let countValuesByKey = (arr, key) =>
arr.reduce((r, c) => {
r[c[key]] = (r[c[key]] || 0) + 1;
return r;
}, {});
//returns numbers only
let countValue = (arr, key, value) =>
arr.filter((x) => x[key] === value).length;
console.debug("dutyCount", countValuesByKey(dutyCount, "text"));
return dutyCount;
},
Expected Output:
{
"Team A": 2,
"Team B": 3
}