Daniel Smith
Daniel Smith

Reputation: 1734

How to replace white space and remove special characters from all keys of an object

I have following array object - in where I want to replace all white space with underscore (_) mark and remove all special characters form all key of the object in forEach loop.

Array Input:

[{
    "Location Number": 49,
    "Location Full Name": "New York",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
},
{
    "Location Number": 44,
    "Location Full Name": "New Jersey",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
}]

Expected output:

[{
    "Location_Number": 49,
    "Location_Full_Name": "New York",
    "Location_Status": "OPEN",
    "RegionState": "NY",
    "Postal_Code": 10010,
    "Country": "USA",
    "Location_Email_Address": "[email protected]",
    "Location_Telephone_Number": "(123) 233 4453",
    "Node_Type": "Retail Store",
    "User_Login_Location": "Yes"
},
{
    "Location_Number": 44,
    "Location_Full_Name": "New Jersey",
    "Location_Status": "OPEN",
    "RegionState": "NY",
    "Postal_Code": 10010,
    "Country": "USA",
    "Location_Email_Address": "[email protected]",
    "Location_Telephone_Number": "(123) 233 4453",
    "Node_Type": "Retail Store",
    "User_Login_Location": "Yes"
}]

JavaScript:

inputArray.forEach(function (item, index, object) {
    const key = Object.keys(item);
    console.log(key);
    key.forEach(function(){
        // somthing
    });
});

Upvotes: 1

Views: 1927

Answers (5)

maioman
maioman

Reputation: 18744

What you're asking could be achieved casting to tuple, transforming the keys, and then recreating each object (with Object.entries and Object.fromEntries methods):

     const rmWhite = o => Object.fromEntries(Object.entries(o).map(([k,v]) => [k.replace(/ /g,  '_'), v]))
     const res = inputArr.map(rmWhite)

In the example I'm only replacing the white spaces with _ , if you want other manipulations you'll need to add them in the map callback.


Edit: below you can find a full snippet for the solution using only one regex (switching between cases inside the regex callback):

const inputArr = [{
    "Location Number": 49,
    "Location Full Name": "New York",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
  },
  {
    "Location Number": 44,
    "Location Full Name": "New Jersey",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
  }
];

const subsChars = o => Object.fromEntries(Object.entries(o).map(
  ([k, v]) => [k.replace(/[ \W]/g, m => m === ' ' ? '_' : ''), v]
))
const res = inputArr.map(subsChars)

console.log(res)

Upvotes: 1

Shravan Dhar
Shravan Dhar

Reputation: 1560

This is concise and exactly what you need:

const arr = [{
    "Location Number": 49,
    "Location Full Name": "New York",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
},
{
    "Location Number": 44,
    "Location Full Name": "New Jersey",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
}];

for (let i = 0; i < arr.length; i++) {
    let obj = {};
    for (let [key, value] of Object.entries(arr[i])) {
        filterKey = key.replace(/\s+/g, "_")       // remove spaces
                       .replace(/\W+/gm, "");  // remove special chars
        obj[filterKey] = value;
    }
    arr[i] = obj;
}

console.log(arr);

Upvotes: 0

Giovanni Esposito
Giovanni Esposito

Reputation: 11156

Ciao, you could use a split and join functions to replace " " with "_", and a replace to remove special chars, like:

let input = [{
    "Location Number": 49,
    "Location Full Name": "New York",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
},
{
    "Location Number": 44,
    "Location Full Name": "New Jersey",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
}]

let result = input.map(el => {
    let resultobj = {};
    Object.entries(el).map(([key, val]) => {      
      resultobj[key.split(" ").join("_").replace(/\W+/g, '')] = val;
      return resultobj;
} )
  return resultobj;
})

console.log(result)

Upvotes: 1

Always Helping
Always Helping

Reputation: 14570

You could do this by using Array#Map and Array#ForEach with replace and a simple Regex to replace all spaces with an underscore.

Edit: Just noticed that you want / removed as well from Region/State - I have added that ReGex as well to match the exact expected output.

Live Demo:

var inputArray = [{
    "Location Number": 49,
    "Location Full Name": "New York",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
  },
  {
    "Location Number": 44,
    "Location Full Name": "New Jersey",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
  }
]

var newArray = []
inputArray.map(function(item, index, object) {
  const result = {}; //store new entries
  Object.keys(item).forEach(function(x) {
    result[x.replace(/ +/g, '_').replace(/\W+/g, '')] = item[x]; //replace space with _
  });
  newArray.push(result) //push new results
});

console.log(newArray) //new Array

Upvotes: 0

felixmosh
felixmosh

Reputation: 35503

In order the "clean" the keys you need to use 2 regexs:

  1. .replace(/\s+/g, '_') which will replace whitespace chars into _
  2. .replace(/\W+/g, '') which will replace none alphanumeric chars into ''

const input = [{
    "Location Number": 49,
    "Location Full Name": "New York",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
  },
  {
    "Location Number": 44,
    "Location Full Name": "New Jersey",
    "Location Status": "OPEN",
    "Region/State": "NY",
    "Postal Code": 10010,
    "Country": "USA",
    "Location Email Address": "[email protected]",
    "Location Telephone Number": "(123) 233 4453",
    "Node Type": "Retail Store",
    "User Login Location?": "Yes"
  }
];

function changeKeys(item, index) {
  return Object.keys(item).reduce((result, key) => {
    const cleanKey = key.replace(/\s+/g, '_').replace(/\W+/g, '')
    result[cleanKey] = input[index][key];
    return result;
  }, {});

}

const result = input.map(changeKeys)

console.log(result);

Upvotes: 3

Related Questions