Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to trim() space characters off all Properties in a JavaScript Object as they are being set?

This is a stripped down demo with the very basic needed to replicate what I need to do.

In my JavaScript application I have a Click event on Project Task Records.

When a Task is clicked on, I populate a JavaScript Object with data from the DOM related to the clicked on Task record.

My problem is that, when I print out the values saved to my object from the DOM, there is always massive space characters in front and behind my strings.

enter image description here

I have this Shim to utilize the newer built in JavaScript trim() function...

/* JavaScript trim() method is ES 5, just in case polyfill it (IE 8 and down):
 * example usage:
 *  var str = " a b    c d e   f g   ";
 *  var newStr = str.trim();
*/
if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '');
  };
}

Below I have a simple demo thrown together for this question.

You will see a JavaScript Object stored in taskDataObject

(NOTICE: I realize the actual selector code below is disgusting, that is next on my to-do list!)

This JSFiddle page has all the code to show my demo running:
http://jsfiddle.net/jasondavis/2hkz0gp4/

When .taskName is clicked on, it grabs data from the DOM and saves it to the taskDataObject JavaScript Object.

I am looking for a good way to apply this str.trim() code to all the properties in taskDataObject and was hoping I wouldn't have to make a bunch of temporary variables.

Demo code

//Open Task Modal when a Task record is clicked in Task List
$('body').on('click', '.taskName', function() {


    // Set and Cache Task ID from clicked on Task Item
    var taskId = $(this).parent().parent().parent().dataAttr('task-id');

    var $taskEl = $(this);

    // Populate Task Data Object from DOM values
    taskDataObject = {
        //projectId: projectTaskModal.cache.projectId,
        taskId: taskId,
        taskName: $taskEl.text(),
        taskDescription: $taskEl.next('.description').text(),
        taskStatus: $taskEl.parent().parent('td').next().text(),
        taskPriority: $taskEl.parent().parent('td').next().next().text(),
        taskTags: $taskEl.parent().parent('td').next().next().next().text(),
        taskCreatedDate: $taskEl.parent().parent('td').next().next().next().next().text(),
        taskModifiedDate: $taskEl.parent().parent('td').next().next().next().next().next().text(),
        taskDueDate: $taskEl.parent().parent('td').next().next().next().next().next().next().text(),
    };

    console.log('taskDataObject', taskDataObject);


    // Just playing around, this applies the trim() however I had
    // to create a bunch of temp variables and I am not sure if 
    // this can be avoided or done differently?
    for (var key in taskDataObject) {

      if (taskDataObject.hasOwnProperty(key)) {

        alert(key + " -> " + taskDataObject[key]);

        //console.log(key + " -> " + taskDataObject[key]);

          console.log(taskDataObject[key]);

          var tmpVal1 = taskDataObject[key]
          var tmpVal2 = tmpVal1.trim();

          console.log(tmpVal2);

      }
    }

});
like image 810
JasonDavis Avatar asked May 07 '15 21:05

JasonDavis


1 Answers

If i understand your problem correctly, you just need to call text().trim() instead of text(). text() returns a String

In case you really need to do the trim for each property value, do:

for (var key in taskDataObject) {
    if(taskDataObject[key].trim)
       taskDataObject[key] = taskDataObject[key].trim(); 
}

And here is a function to do it recursively, along all child properties:

function trimObjectProperties(objectToTrim) {
    for (var key in objectToTrim) {
        if (objectToTrim[key].constructor && objectToTrim[key].constructor == Object)
            trimObjectProperties(objectToTrim[key]);
        else if (objectToTrim[key].trim)
            objectToTrim[key] = objectToTrim[key].trim();
    }
}

// Using this function, you should call it in that way:
trimObjectProperties(taskDataObject);
like image 168
Diego ZoracKy Avatar answered Oct 13 '22 00:10

Diego ZoracKy