1

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>

2
  • What would be your expected output for this data sample? Commented Mar 19, 2020 at 17:30
  • sorry, forgot to mention, I'm stuck using ECMAScript 5. it doesn't support => But I might be able to convert that. Commented Mar 19, 2020 at 21:01

2 Answers 2

2

You can use reduce and data and service combination string as key to count.

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 res = storage.reduce(function (x, cur) {
    let item = cur.data + cur.award
    if (!x[item]) x[item] = 0;
    x[item] = x[item] + 1
    return x
}, {})
var results = []

for (const key in res) {
    const count = res[key];
    const data = key.slice(0, 2)
    const service = key.slice(2)
    results.push({
        data: data,
        service: service,
        count: count
    })
}
console.log(results)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, xdeep, sorry, forgot to mention, I'm stuck using ECMAScript 5. it doesn't support => But I might be able to convert that. I noticed it's just pulling the DDR.
Thanks, xdeepakv, I have to mark this as more correct because it literally answers the question and provides a working example based on the end formatted JSON (ultimate goal) in my question
Thanks buddy!! KEEP CODING?!!
1

You could build a nested object with the counts of wanted keys.

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' }],
    keys = ['data', 'service', 'award'],
    counts = storage.reduce(function (r, o) {
        var last = o[keys[keys.length - 1]],
            reference = keys
                .slice(0, -1)
                .reduce(function (q, k) { return q[o[k]] = q[o[k]] || {}; }, r);
        reference[last] = (reference[last] || 0) + 1;
        return r;
    }, {});

console.log(counts);

6 Comments

thanks, Nina, sorry, forgot to mention, I'm stuck using ECMAScript 5 but maybe i can convert this
Babel to the rescue!
Funny you should say that. I did that but it didn't translate correctly. Only some items turned out in the output. Nevermind, codepen wasn't showing all of the results but they were there. Strange, I wonder why codepen wouldn't show the break out. Either way, thanks Nina
The only issue I'm having now is that I lost my generic keys (service, etc). Trying to get this data into datatables, which wants keys
Nina, is there a way to flatten this. From: { "CT": { "Food": { "DDM": 1 } }, TO: {"data": "CT","service": "Food", "DDM": 1}
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.