Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concat object value with string

I have an api response in react native as

url_string = "https://example.com/"
//JSON Response

product_images: [
    {
        "url": "79/79B20211213054555pm1.jpeg"
    },
    {
        "url": "18/18c20211213054555pm2.jpeg"
    }
]

Now the thing is i want to append the url_string for each of the value as below with

//Expected Outcome - 

"new_product_images": [
    {
        "url": "https://example.com/79/79B20211213054555pm1.jpeg"
    },
    {
        "url": "https://example.com/18/18c20211213054555pm2.jpeg"
    }
]

My attempt

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let product_images = [{
  "url": "79/79B20211213054555pm1.jpeg"
}, {
  "url": "99/79B20211213054555pm1.jpeg"
}];


Object.keys(product_images).forEach(function(key, i) {
  product_images[key] += "example/in";
});
console.log(product_images);

>Solution :

Copy and modify

If you do NOT copy, you may change the original array’s URL object

let product_images = [{
  "url": "79/79B20211213054555pm1.jpeg"
}, {
  "url": "99/79B20211213054555pm1.jpeg"
}];


const prefix = 'https://example.com';
const newImages = JSON.parse(JSON.stringify(product_images)); // deep copy
newImages.forEach(item => item.url = prefix + item.url); // modify
console.log(newImages)
console.log(product_images); // not modified

Shorter if in place modification

let product_images = [{
  "url": "79/79B20211213054555pm1.jpeg"
}, {
  "url": "99/79B20211213054555pm1.jpeg"
}];


const prefix = 'https://example.com';
product_images.forEach(item => item.url = prefix + item.url); // modify
console.log(product_images); // now modified

WATCH OUT, IT’S A TRAP

This does not work as expected

let product_images = [{
  "url": "79/79B20211213054555pm1.jpeg"
}, {
  "url": "99/79B20211213054555pm1.jpeg"
}];
const baseUrl = "https://example.com/",
  newImages = product_images
    .map(image => (image.url = baseUrl + image.url, image));

console.log(newImages)
console.log(product_images); // oops - modified too
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading