gpt4 book ai didi

javascript - 替换以下划线开头的名称

转载 作者:行者123 更新时间:2023-12-03 08:52:57 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来将以下划线开头的名称替换为带破折号的名称。如果第一个字符以下划线开头,则将其替换为破折号。到目前为止我已经做了以下工作;但我需要一些帮助来对嵌套对象递归地执行此操作;我正在寻找一种优雅的方式来做到这一点:

    var myObj = { name: 'foo',
bar: {"_foo": {'_bar':{}}},
'_baz': {}};


Object.prototype.replaceUnderscores = function rec() {
for (var item in this){
if(typeof this[item] == "object"){
this[item] = rec(this[item])
}
if(_.startsWith(item, '_')){
console.log(item)
var newName = item.replace(item[0],'-')
this[newName] = this[item];
delete this[item]
}
}
return this;
};

myObj.replaceUnderscores()

console.log(myObj);

最佳答案

我在尝试您的代码时遇到了一些错误(_在startsWith调用中未定义)。也没有看到需要命名该函数,因为它被指定为原型(prototype),但以下工作有效:

var myObj = { 
name: 'foo',
bar: {
"_foo": {
'_bar': {}
}
},
'_baz': {}
};

console.log('before: %o', myObj);

Object.prototype.replaceUnderscores = function() {
for (var item in this){
if(typeof this[item] == "object"){
this[item] = this[item].replaceUnderscores();
}

if(item.startsWith('_')){

var newName = item.replace(item[0],'-');
console.log(item + ' / ' + newName);
this[newName] = this[item];
delete this[item]
}
}
return this;
};

console.log('after: %o', myObj.replaceUnderscores());

工作中fiddle

更新

我现在看到了错误。你说的地方

this[item] = rec(this[item])

我说

this[item] = this[item].replaceUnderscores();

即使您为函数命名,您也不​​会将要更改的对象作为参数传递 - 它是对象原型(prototype)的一部分,并且适用于 this

关于javascript - 替换以下划线开头的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32617357/

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