0

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 ?

1
  • Be aware that you need to escape the special characters in your regex. You could however do .split('.').pop() to get url1, url2 and so forth. Commented Sep 23, 2016 at 23:36

5 Answers 5

2

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.', '')
}))
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

1

You could just iterate over the array like this:

array.forEach(function(entry) {
    entry.url = entry.url.replace('http://www.','');
});

Comments

1

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);

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.