[英]Replace dot to underscore in js object keys names
我需要遍历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"
}
使用lodash ,这是一个函数,该函数将对象的每个键的下划线递归替换为下划线。
并添加了测试以验证结果。
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 = { "aa": { "nee.cc": "sdkfhkj" }, "bb": "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>
使用Array.prototype.reduce()
创建一个新对象,并使用不带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({"aa":"test", "bb": "anotherProp"}); console.log(result);
下面的这段代码可能有助于您解决问题。
Object.keys(yourObj).forEach(function(v){
yourObj[v.replace(".", "_")] = yourObj[v];
delete yourObj[v];
console.log(yourObj);
});
您可以只使用键为“ _”而不是“”的属性填充新对象。 :
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' }
使函数循环您的对象并检查是否有对象,然后重用函数。
var obj = {
"a.a":{
"nee.cc":"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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.