2017-03-09 32 views
0

有谁知道如何做一个匹配和替换的JavaScript对象的价值?例如:如何做一个匹配和替换JavaScript对象

var obj = { 
    name: '/asdf/sdfdsf/:_id', 
    type: 'dfdfdf' 
} 

obj.name = obj.replace(':_id', 'replacement'); 

我希望得到的对象是:

obj = { 
    name: '/asdf/sdfdsf/replacement', 
    type: 'dfdfdf' 
} 

然而,这给我的错误obj.replace is not a function。有人可以帮忙吗?

+1

字符串化的对象,并做了更换。 –

回答

2

String.prototype.replace()应用在一个字符串,而不是一个对象,这里是工作的代码

var obj = { 
 
    name: '/asdf/sdfdsf/:_id', 
 
    type: 'dfdfdf' 
 
} 
 

 
// change is here 
 
obj.name = obj.name.replace(':_id', 'replacement'); 
 

 
console.log(obj)

1

您可以在对象上使用replace函数。使用Object.keys()代替捕获每个属性并替换它的密钥。

var obj = { 
 
    name: '/asdf/sdfdsf/:_id', 
 
    type: 'dfdfdf' 
 
} 
 

 
//if you want to change :_id in few keys 
 
var res = Object.keys(obj).map(v => obj[v].replace(':_id', 'replacement')); 
 
console.log(res); 
 

 
//if you want to change it only in one, specified property - use direct reference 
 
var singleObj = obj.name.replace(':_id', 'replacement'); 
 
console.log(singleObj);

+0

这是一个更一般的解决方案,但是如果值是另一个对象,则替换会抛出,所以您可能想要检查并返回或递归执行(深) – lustoykov

+0

@leo您的解决方案(针对他的特定问题的解决方案)似乎太过简单甚至打扰做出自己的答案......我只是想补充一些额外的东西。 –

+1

我同意,我的解决方案很简单,但完整,因为它只涵盖了一个非常具体的用例。提出的一个试图更普遍,但工作只是一半,可能会打破。不要批评,只是建议使其完整,所以OP可以接受你的答案,因为它会更好: - ) – lustoykov

0

您可以在对象取代单串:

obj.name = obj.name.replace (':_id', 'replacement') 

如果你想更换所有字符串对象:

for (x in obj) { 
    if (typeof (obj[x]) == 'string') 
     obj [x] = obj [x].replace (':_id', 'whee!') 
} 

如果你是某个对象仅包含字符串,你可以删除“如果”从环路。这是非递归的。

0

如果您需要替换对象,您可以使用一个这样的功能。

var obj = { 
 
    name: '/asdf/sdfdsf/replacement/_id', 
 
    type: 'dfdfdf' 
 
}; 
 
var replaceInObject=function(object,word,value){ 
 
    var string=JSON.stringify(object); 
 
    string=string.replace(word,value); 
 
    object=JSON.parse(string); 
 
    return object; 
 
} 
 

 
console.log(replaceInObject(obj,'_id','testID'));