最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Replace dot to underscore in js object keys names - Stack Overflow

matteradmin3PV0评论

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":"sdkfhkj"
},
"b.b": "anotherProp"
}

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":"sdkfhkj"
},
"b.b": "anotherProp"
}
Share edited Nov 2, 2016 at 14:28 OlegL asked Nov 2, 2016 at 13:35 OlegLOlegL 3594 silver badges13 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

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": "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./ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Create a new object using Array.prototype.reduce(), and replace the the dot in the props's names using a simple string replace without regexp:

function transformKeys(obj) {
  return Object.keys(obj).reduce(function(o, prop) {
    var value = obj[prop];
    var newProp = prop.replace('.', '_');
    o[newProp] = value;
    return o;
  }, {});
}

var result = transformKeys({"a.a":"test", "b.b": "anotherProp"});

console.log(result);

Make a function for loop your object and check has object , then reuse function .

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

d_u(obj); // change dot to underscore function

function d_u(obj){
    for(var i in obj) {
        if (typeof obj[i] == "object") d_u(obj[i]);            
            obj[i.replace(/\./g,'_')] = obj[i];            
            delete obj[i];  // delete old object [current]      
    }
}
console.log(obj);

This below code might help you resolving your issue.

Object.keys(yourObj).forEach(function(v){
    yourObj[v.replace(".", "_")] = yourObj[v];
    delete yourObj[v];
    console.log(yourObj);
});

You can just populate a new object with properties whose keys are with "_" rather than "." :

var transformKeys = obj => {
  result = {};
  Object.keys(obj).forEach(x => {
    var y = x.replace(".", "_");
    result[y] = obj[x];
  });
  return result;
}
console.log(transformKeys({"a.a":"test", "b.b": "anotherProp"}));
// { a_a: 'test', b_b: 'anotherProp' }
Post a comment

comment list (0)

  1. No comments so far