preloader
軟體工程

Using Coffeescript to classify objects based on their value of attributes

We could classify objects of javascript or JSON ones to different groups based on their attributes' values. I modified original example as below coffeescript code from Reference link.

Suppose you have an array-variable of JSON objects and a variable of Object, and you want to classify or group them based on values of their date attributes. 

warehouseOfClassifiedJSONObj = new Object();
arrayOfJSONObj = [
  {name:"taro", date:"1996-01-01", total_average_price: 50},
  {name: "flower", date: "1996-01-02", total_average_price: 70}, 
  {name:"taro", date:"1996-01-02", total_average_price: 52}, 
  {name:"sunkist", date:"1996-01-01", total_average_price: 50}, 
  {name:"broccoli", date:"1996-01-03", total_average_price: 30}
  ];
for (element in arrayOfJSONObj) {
  warehouseOfClassifiedJSONObj[element['date']] = warehouseOfClassifiedJSONObj[element['date']] || []; # important step for checking whether attributes in object is exist. If it doesn't exist, store an empty array into value of this attribute.
  warehouseOfClassifiedJSONObj[element['date']].push(element); # store classified object into array
}

keysOfWarehouse = Object.keys(warehouseOfClassifiedJSONObj); # prepare keys for printing classified object in array

for (element in keysOfWarehouse ){
  arrayOfAttributesValue = warehouseOfClassifiedJSONObj[element]
  console.log("group " + element + ":");
  for item in arrayOfAttributesValue {
   console.log(item); # print item's content at browsers' console
  }
}

console.log will print them as below in order:

group 1996-01-01:

{name: "taro", date: "1996-01-01", total_average_price: 50}

{name: "sunkist", date: "1996-01-01", total_average_price: 50}

group 1996-01-02:

{name: "flower", date: "1996-01-02", total_average_price: 70}

{name: "taro", date: "1996-01-02", total_average_price: 52}

group 1996-01-03:

{name: "broccoli", date: "1996-01-03", total_average_price: 30}

 

The following and similar method modified from aboved important step block and create is motivated from Reference link:

if (warehouseOfClassifiedJSONObj[element['date']]?.length) {
  warehouseOfClassifiedJSONObj[element['date']].push(element);
}
else {
  warehouseOfClassifiedJSONObj[element['date']] = [element];
}

 

Reference: 

http://codereview.stackexchange.com/questions/37028/grouping-elements-in-array-by-multiple-properties/37132#37132