Search code examples
javascriptpropertiestrim

JavaScript trim all own property key names of an object?


How to trim all own (not inherited) property keys / names of an object? To trim the key name, not the property's value.

PS. Closest similar question I found is about trimming property values: javascript : trim all properties of an object

EDIT: This question was suggested as a possible duplicate. However, I'm explicitly needing to trim just the key name, not the value: Trim white spaces in both Object key and value recursively


Solution

  • As far as i understood, Object.keys() or Object.entries() should do the job.

    const obj = { "a " : 1 , "   b " : 2 };
    
    const trimmed = Object.entries(obj).reduce((acc, curr) => {
      let [key, value] = curr;
      // Checking if the key is a string
      acc[typeof key === "string" ? key.trim() : key] = value; 
      return acc;
    }, {});
    
    console.log(trimmed); // -> { a: 1, b: 2 } notice the trimmed keys