Search code examples
node.jsobjectjavascript-objects

NODE.JS: iterating over an array of objects, creating a new key if it does not exist


I am iterating over a collection of data, in my case, an array of objects. Here is a sample of 2 data points from it:

 {
violation_id: '211315',
inspection_id: '268804',
violation_category: 'Garbage and Refuse',
violation_date: '2012-03-22 0:00',
violation_date_closed: '',
violation_type: 'Refuse Accumulation' },

{
violation_id: '214351',
inspection_id: '273183',
violation_category: 'Building Conditions',
violation_date: '2012-05-01 0:00',
violation_date_closed: '2012-04-17 0:00',
violation_type: 'Mold or Mildew' }

I need to create a new array of objects from this, one for each "violation_category" property. If Violation category already exists in the new array I am creating, i simply add the information to that existing category object (instead of having two "building conditions" objects for example, I would just add to an existing one).

However, I am having trouble assigning to the existing object if the current one exists (it's easy to check if it does not, but not the other way around). This is what am attempting to do currently:

    if (violationCategory.uniqueCategoryName) {
  violationCategory.uniqueCategoryName.violations = results[i].violation_id;
  violationCategory.uniqueCategoryName.date = results[i].violation_date;
  violationCategory.uniqueCategoryName.closed =
    results[i].violation_date_closed;
} else {
  category.violations = results[i].violation_id;
  category.date = results[i].violation_date;
  category.closed = results[i].violation_date_closed;
  violationCategory.push(category);
}

In first condition, if this category (key) exists, I simply add to it, and in the second condition, this is where I am struggling. Any help appreciated. Thanks guys.


Solution

  • Just add an empty object to the key if there no object there :

    violationCategory.uniqueCategoryName = violationCategory.uniqueCategoryName || {};
    

    And only then, add the data you want to the object.

       violationCategory.uniqueCategoryName.violations = results[i].violation_id;
       violationCategory.uniqueCategoryName.date = results[i].violation_date;
       violationCategory.uniqueCategoryName.closed =
       results[i].violation_date_closed;
    

    No condition needed.

    Good luck!