Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace dot to underscore in js object keys names

Tags:

javascript

key

I need to walk js object and replace all dots to underscores in this object keys.
For example

{a.a:"test"}
to
{a_a:"test"}

This is my code.

Object.getOwnPropertyNames(match).forEach(function(val, idx, array) {
    if(val.indexOf(".") != -1){
       val.replace(/\./g,'_');
    }
});

Thanks, but I have problem in object not so simple, like this

{
"a.a":{
   "nee.cc":"sdkfhkj"
},
"b.b": "anotherProp"
}
like image 913
OlegL Avatar asked Nov 02 '16 13:11

OlegL


People also ask

Can I change key name in object JavaScript?

To rename a key in an object:Use bracket notation to assign the value of the old key to the new key. Use the delete operator to delete the old key. The object will contain only the key with the new name.

How do I change the value of a key in an object?

To update all the values in an object:Use the Object. keys() method to get an array of the object's keys. Iterate over the array using the forEach() method and update each value. After the last iteration, all the values in the object will be updated.

Can JavaScript object have same keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

How do I change the key of an object in node JS?

Syntax: obj['New key'] = obj['old key']; Note: Renaming the object by simple assignment of variable could be applied on multiple key, value pairs.


1 Answers

Using lodash, here's a function that will recursively replace the dots with underscores for each of the object's keys.

And added a test to verify results.

function replaceDotWithUnderscore(obj) {
  _.forOwn(obj, (value, key) => {

    // if key has a period, replace all occurences with an underscore
    if (_.includes(key, '.')) {
      const cleanKey = _.replace(key, /\./g, '_');
      obj[cleanKey] = value;
      delete obj[key];
    }

    // continue recursively looping through if we have an object or array
    if (_.isObject(value)) {
      return replaceDotWithUnderscore(value);
    }
  });
  return obj;
}

// --------------------------------------------------
// Run the function with a test to verify results
// -------------------------------------------------

var input = {
  "a.a": {
    "nee.cc": "sdkfhkj"
  },
  "b.b": "anotherProp"
};

var result = replaceDotWithUnderscore(input);

// run a quick test to make sure our result matches the expected results...
var expectedResult = {
  "a_a": {
    "nee_cc": "sdkfhkj"
  },
  "b_b": "anotherProp"
};

console.log(result);
console.assert(_.isEqual(result, expectedResult), 'result should match expected result.');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 153
pbojinov Avatar answered Oct 05 '22 13:10

pbojinov