Home > OS >  How does one map an array in order to create both a new array with changed array items but without m
How does one map an array in order to create both a new array with changed array items but without m

Time:01-18

I have an array of objects for example I want to replace the key normal with value www.test.com/is/images/383773?@HT_dtImage. I am using .replace with regex to basically replace the wid and hei with @HT_dtImage

const urls = [
{"normal": "www.test.com/is/images/383773?wid=200&hei=200", 
"thumbnail": "www.test.com/is/images/383773?wid=200&hei=200"},
{"normal": "www.test.com/is/images/383773?wid=200&hei=200",
 "thumbnail": "www.test.com/is/images/383773?wid=200&hei=200"},
{"normal": "www.test.com/is/images/383773?wid=200&hei=200",
 "thumbnail": "www.test.com/is/images/383773?wid=200&hei=200"}
]

I tried using a .map like this which just returns the original object.

const updateImages = images => {
  images.map(image => {
    return image.normal.replace(/\b(?:wid|hei)=[^&]*&?/g, "")   "@HT_dtImage"
  });
  return images;
};

I also tried this but it returns it in an array without not as an array with objects. I feel like I'm just missing something simple.

const updateImages = images => {
   return images.map(image => {
     return image.normal.replace(/\b(?:wid|hei)=[^&]*&?/g, "")   "@HT_dtImage"
  })
};

The expected output I am looking for is

const urls = [
{"normal": "www.test.com/is/images/383773?@HT_dtImage", 
"thumbnail": "www.test.com/is/images/383773?wid=200&hei=200"},
{"normal": "www.test.com/is/images/383773?@HT_dtImage",
 "thumbnail": "www.test.com/is/images/383773?wid=200&hei=200"},
{"normal": "www.test.com/is/images/383773?@HT_dtImage",
 "thumbnail": "www.test.com/is/images/383773?wid=200&hei=200"}
]

CodePudding user response:

The OP not only needs to enter image description here

CodePudding user response:

On your first try, images.map returns a new array which you don't assign to anything. You are returning the same array as the one passed as parameter.

const newImages = images.map(....);
return newImages

CodePudding user response:

You neen to return an array with some object that have the needed key, so something like:

const updateImages = images => images.map(image => (
  {
     ...image,
     normal: image.normal.replace(/\b(?:wid|hei)=[^&]*&?/g, "")   "@HT_dtImage",
  }
);
  •  Tags:  
  • Related