gpt4 book ai didi

javascript - 将js对象键名称中的点替换为下划线

转载 作者:数据小太阳 更新时间:2023-10-29 06:15:01 25 4
gpt4 key购买 nike

我需要遍历 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 = {
"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>

关于javascript - 将js对象键名称中的点替换为下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40381329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com