Simon Breton Simon Breton - 2 months ago 13
Javascript Question

Modifying key string in array object

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 ?

Answer

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.', '')
}))
Comments