0

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

ux.engineer
  • 10,082
  • 13
  • 67
  • 112
  • Does this answer your question? [Trim white spaces in both Object key and value recursively](https://stackoverflow.com/questions/33510625/trim-white-spaces-in-both-object-key-and-value-recursively) – Anurag Srivastava Apr 02 '20 at 09:21
  • This question is about trimming just the key name, not the value. However thanks for linking that question as it has some helpful approaches. – ux.engineer Apr 02 '20 at 09:40

2 Answers2

2

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
ux.engineer
  • 10,082
  • 13
  • 67
  • 112
mgreif
  • 131
  • 6
0

You could test if the key is a string (and not Symbol) and trim this value and get a new object with Object.fromEntries

const
    obj = { "a " : 1 , "   b " : 2 },
    trimmed = Object.fromEntries(Object.entries(obj).map(([k, v]) => [
        typeof k === 'string' ? k.trim() : k,
        v
    ]));

console.log(trimmed);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392