Search code examples
javascriptarraystrim

How to trim All Keys in an Array?


I have the potential on creating an Array from reading an Excel spreadsheet that the Column Headers, which will end up as my Array Keys, may have leading and/or trailing spaces. I'd like to check and trim all my keys in my array.

I tried the following but it did not seem to work

let trimmedKeyData = Object.keys(data).forEach(k => k = k.trim());

If I want to achieve this, I wondered what the best Javascript functions for doing so are?


Solution

  • You can't rename a key in an object. You can delete and re-create a property or create a new object. You may try to do it in the same order as you iterate on it, but the final order is not guaranteed.

    var arr = [{
        "COL A   ": 1,
        "COL B   ": 2,
        "COL C": 3,
      },
      {
        "COL A   ": 4,
        "COL B   ": 5,
        "COL C": 6,
      }
    ]
    
    var newArr = arr.map(function(item) {
      var newItem = Object.keys(item).reduce(function(agg, key) {
        agg[("" + key).trim()] = item[key]
        return agg;
      }, {})
      return newItem
    })
    
    console.log(newArr)
    .as-console-wrapper {
      min-height: 100%;
    }