我需要遍历 js 对象并将该对象键中的所有点替换为下划线。
例如
{a.a:"test"}
to
{a_a:"test"}
这是我的代码。
Object.getOwnPropertyNames(match).forEach(function(val, idx, array) {
if(val.indexOf(".") != -1){
val.replace(/\./g,'_');
}
});
谢谢,但我的对象问题不那么简单,
像这样
{
"a.a":{
"nee.cc":"sdkfhkj"
},
"b.b": "anotherProp"
}
Using lodash https://lodash.com/docs/4.17.4,这是一个函数,它将递归地将对象的每个键的点替换为下划线。
并添加了一个测试来验证结果。
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)