Reputation: 2876
I have the following array of object :
[{url:"http://www.url1",value: "number1"},{url:"http://www.url2",value: "number2"},{url: "http://www.url3", value: "number3"},etc...]
I would like to replace all the http://www.
with an empty string.
looking at some answers, I've found this :
var resultArr = arr.map(function(x){return x.replace(/http://www./g, '');});
However it doesn't apply in my case since map
is only working for array.
so I've also look at this :
array = [{url:1,value: 2},{url:3,value: 4},{url: 5, value: 6}]
Object.keys(array).map(function(url, value) {
array[value] *= 2;
});
but return me this : [undefined, undefined, undefined]
. Moreover for this last solution I don't really know where I should use .replace(/,/g, '')
method...
any idea ?
Upvotes: 0
Views: 67
Reputation: 4783
var array = [{url:"http://www.url1",value: "number1"},{url:"http://www.url2",value: "number2"},{url: "http://www.url3", value: "number3"}];
for (var i=0 ; i < array.length ; i++){
array[i].url = array[i].url.replace("http://www.", "");
};
console.log(array);
Upvotes: 1
Reputation: 643
es5:
array.map(function(element) {
return {
value: element.value,
url: element.url.replace('http://www.', '')
}
})
es6+:
array.map(element => ({
...element,
url: element.url.replace('http://www.', '')
}))
Upvotes: 2
Reputation: 39386
You're almost there! map
is not really the way to go, since you want to modify the items of the list. forEach
makes more sense
var lst = [{
url: "http://www.url1",
value: "number1"
}, {
url: "http://www.url2",
value: "number2"
}, {
url: "http://www.url3",
value: "number3"
}];
lst.forEach(obj =>
Object.keys(obj)
.forEach(key =>
obj[key] = obj[key].replace(/http:\/\/www\./g, '')));
console.log(lst);
Upvotes: 1
Reputation: 1889
You could just iterate over the array like this:
array.forEach(function(entry) {
entry.url = entry.url.replace('http://www.','');
});
Upvotes: 1
Reputation: 350087
You need to get the syntax right. map
is OK, or in this case forEach
as you mutate:
var array = [{url:'http://www.example.com?xyz',value: 2},
{url:'http://www.example.com?ok',value: 4},
{url:'http://www.example.com?hello', value: 6}]
array.forEach(function(obj) {
obj.value *= 2;
obj.url = obj.url.replace(/http:\/\/www\./g, '');
});
console.log(array);
Upvotes: 2