I am trying to loop thru an array of objects and get a count of similar values for a particular key when certain conditions are met. I tried looping on one array (storage) first but then realized that conditions had to be dynamic. They are not now. I entered in HR and Food but would ideally like to make those variables. So I'm looping thru values in arrayC and cross checking against storage for those value. If I loop once (have only one value in arrayC), it works but more than that, it loops too many times and gives me incorrect output. Trying to get a count of all similar award properties as it correlates to data and service. Example, so all objects with data: "HR" and Service: "Food" would be combined to reflect: {data:HR, service:Food, DDR: 3}
Code:
var arrayC = ["DDM","DDR"];
var storage = [
{ data: 'CT', service: 'Food',award: 'DDM' },
{ data: 'HR', service: 'Food',award: 'DDM' },
{ data: 'HR', service: 'Food',award: 'DDR' },
{ data: 'HR', service: 'Food',award: 'DDR' },
{ data: 'HR', service: 'Food',award: 'DDR' }
];
var array1=[];
var arrayTest = [];
var jk ={};
function getIt () {
arrayC.forEach(function(key,value){
$.each(storage, function(k,x){
// console.log(v.award);
if(key==x.award&&x.data=="HR"&&x.service=="Food"){
jk[x.award] = jk.hasOwnProperty(x.award) ? arrayTest.push(x.award) : arrayTest.push(x.award),
jk.data = x.data,
jk.service = x.service
}
}); //inside each
});
//array1.push(jk);
return jk;
}
var newThing = getIt();
console.log(newThing);
//Output:
//Object {
// data: "HR",
// DDM: 1,
// DDR: 4,
// service: "Food"
//}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>