Mani Lovepreet
Mani Lovepreet

Reputation: 11

How to use name field values of object to count data of other fields in JavaScript

My data object is

var obj=[{"Town":"Newton","PropertyType":"Multi Family","InvestmentType":"Homeownership","Perks":"Retail Store"},
  {"Town":"South Surrey","PropertyType":"Multi Family","InvestmentType":"Investment Property","Perks":"Retail Store"},
  {"Town":"South Surrey","PropertyType":"Multi Family","InvestmentType":"Investment Property","Perks":"Bus Station"},
  {"Town":"South Surrey","PropertyType":"Condo","InvestmentType":"Homeownership","Perks":"Retail Store"}];

I want to calculate the Perks of each Town

Required Outcome:

{name:"South Surrey", data:[2,1]}
//As in south surrey the perks retail store counts to 2, 1 is for bus station.


What I have tried..

var Newtonstats=[];//keeps the count
 var eachRec=[];//handles each rec.

obj.forEach(obj=>{
  
  Object.keys(obj).forEach((key)=>{
    
  if(key=="Town")
  {
    switch(obj.Town)
    {
      case "Newton":
        Object.keys(obj).forEach((secKey)=>{
        
          if(secKey=="Perks")
            {
             
              
              (Newtonstats[obj[secKey]]?
                Newtonstats[obj[secKey]]++:
                Newtonstats[obj[secKey]]=1);
                eachRec[0]={name:"Newton", key: Newtonstats};
              
            }
          
        });
      }
    }
  });


});

  console.log(eachRec[0]);
//Outcome. 
// name:"Newton" ,key[]: 'Retail Store': 1

The problem with this code is that it is hardcoded. I want to dynamically put the values in each name type.

2nd method that i tried.

I tried using obj.hasOwnProperty But i am confused..

var main={}; var counts={};

obj.forEach(function (o) {

if (!main.hasOwnProperty(o.Town)) {
    main[o.Town] =  main[o.Town]+countPerks(obj);
}
// increment the count based on the type
main[o.Town] +=  countPerks(obj);

});

function countPerks(objects) {

objects.forEach(function (o) {

if (!counts.hasOwnProperty(o.Perks)) {
    counts[o.Perks] = 0;
}
// increment the count based on the type
counts[o.Perks] += 1;

});

return counts;

}

console.log(main);

Upvotes: 1

Views: 156

Answers (1)

Rajneesh
Rajneesh

Reputation: 5308

You can make use of reduce and assign perks count to that perk. Something like this:

var obj=[{"Town":"Newton","PropertyType":"Multi Family","InvestmentType":"Homeownership","Perks":"Retail Store"}, {"Town":"South Surrey","PropertyType":"Multi Family","InvestmentType":"Investment Property","Perks":"Retail Store"}, {"Town":"South Surrey","PropertyType":"Multi Family","InvestmentType":"Investment Property","Perks":"Bus Station"}, {"Town":"South Surrey","PropertyType":"Condo","InvestmentType":"Homeownership","Perks":"Retail Store"}];

var result = Object.values(obj.reduce((a, {Town, Perks})=>{
    a[Town] = a[Town] || {Town, perks:{}};
    a[Town].perks[Perks] = (a[Town].perks[Perks] || 0) + 1;
    return a;
},{}));

console.log(result);

Upvotes: 1

Related Questions