Search code examples
javascriptjqueryobjecttrim

Cannot trim object properties using Javascript or JQuery


I have not been able to find a way to trim (get rid of the white space at the beginning and end of each string) the properties of the array of objects in my code. Following the advice in other threads on here did not work. I have an array of objects named 'res'. The properties below are in 'res.d'. How can I trim this object and then JSON.parse it as such:

res.d = JSON.parse(res.d) 

Thanks

[{"id":"FARM, LODGE","name":"104"}, 
{"id":"Barn                                            
","name":"124069"},{"id":"Lg\u0027s Barn Fm                                           
","name":"124820"},{"id":"Ld\u0027s Hill Fm                 
","name":"125103"},{"id                             
":"Lord\u0027s Wood Fm                                              
","name":"125126"},{"id":"Lo\u0027s Court Fm                                           
","name":"125345"},{"id":"Lo\u0027s Copse         ","name":"162"}, 
{"id"                                       
:"Lodge              "}]

Solution

  • You could do something like this:

    const items = [
      { id: "       LODGE FARM WEST TO LOWER LODGE FARM, LOWER LODGE", name: "10444" },
      { id: "Hello world             ", name: "5555" }
    ];
    
    const res = items.map(item => {
      return {
        id: item.id.trim(),
        name: item.name.trim()
      };
    });