Reputation: 13751
Does anyone know how to do a match and replace on a javascript object value? For example:
var obj = {
name: '/asdf/sdfdsf/:_id',
type: 'dfdfdf'
}
obj.name = obj.replace(':_id', 'replacement');
I want the resulting object to be:
obj = {
name: '/asdf/sdfdsf/replacement',
type: 'dfdfdf'
}
However, this gives me the error obj.replace is not a function
. Can someone help?
Upvotes: 0
Views: 716
Reputation: 5020
If you need a replace on object you can use one function like that.
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'));
Upvotes: 0
Reputation: 841
You can replace the single string in the object:
obj.name = obj.name.replace (':_id', 'replacement')
If you want to replace all strings in the object:
for (x in obj) {
if (typeof (obj[x]) == 'string')
obj [x] = obj [x].replace (':_id', 'whee!')
}
If you're certain the object only contains strings, you can remove the 'if' from the loop. This is non-recursive.
Upvotes: 0
Reputation: 41893
You can use replace
function on an object. Use Object.keys()
instead to catch every property and replace it's key.
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);
Upvotes: 1
Reputation: 20037
String.prototype.replace() is applied on a string, not an object, here is working code
var obj = {
name: '/asdf/sdfdsf/:_id',
type: 'dfdfdf'
}
// change is here
obj.name = obj.name.replace(':_id', 'replacement');
console.log(obj)
Upvotes: 3