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"
}
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.
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.
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
Syntax: obj['New key'] = obj['old key']; Note: Renaming the object by simple assignment of variable could be applied on multiple key, value pairs.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With