0

I am trying to take an array of objects like so

[
   { url: 'some url here', clickHandler: 'click handler function'},
   { url: 'some other url here', clickHandler: 'other clickHandler function'}
]

I want to pull apart the url of the object and run each url through a function that returns the modified url and return an array like this

[
   { url: 'some modified url here', clickHandler: 'click handler function'},
   { url: 'some other modified url here', clickHandler: 'other clickHandler function'}
]

I know that I want to use .map because I can iterate over the array of objects but I am unsure how to create the new array to have the same structure but just modify the url as necessary. The function is just going to return the modified url.

UPDATE: I don’t want to use forEach because the original array needs to remain intact.

janos
  • 120,954
  • 29
  • 226
  • 236
Mcl0vin
  • 21
  • 4
  • "I don’t want to use forEach because the original array needs to remain intact" it really depends on what you do in the callback. – Mark Schultheiss Oct 06 '17 at 21:10

4 Answers4

1

Easy trick would be:

var newArray = oldArray.map(function(el) {
    el.url = 'new url';   // change url

    return el;          // return whole modified element
});
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
0

Simply return map the array objects as they are except by calling the function that you want to change the url:

var output = input.map(obj => {
  return {
    url: changeUrl(obj.url),
    clickHandler: obj.clickHandler
  }
});

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
  • 1
    I was thinking something like this but I wasn’t 100% sure if it was the right way to go. Thank you! – Mcl0vin Oct 06 '17 at 21:04
0

Use .map() to construct a new object on the fly and return it -

let arr = [

  {
    url: "http://www.foo.com",
    func: () => console.log("Hi")
  },
  {
    url: "http://www.bar.com",
    func: () => console.log("Hi")
  }
];


let modifiedArr = arr.map(e => ({
  url: e['url'] + '/baz',
  func: e['func']
}));

console.log(modifiedArr);
Manish Giri
  • 3,562
  • 8
  • 45
  • 81
0

I would use .map() with Object.assign() so that you don't need to hard code all properties.

var data = [
   { url: 'some url here', clickHandler: 'click handler function'},
   { url: 'some other url here', clickHandler: 'other clickHandler function'}
];

var result = data.map(obj =>
  Object.assign({}, obj, {url: obj.url + " MODIFIED"})
);

console.log(result);

Now if the object structure changes, you don't need to update your code.

llama
  • 2,535
  • 12
  • 11