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
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);
CodePudding user response:
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
CodePudding user response:
You can do it with a general function:
const product_images = [
{
url: '79/79B20211213054555pm1.jpeg',
},
{
url: '18/18c20211213054555pm2.jpeg',
},
];
const concatString = (arr, key, concat) => {
const newArr = arr.map((item) => {
item[key] = concat item[key];
return item;
});
return newArr;
};
console.log(concatString(product_images, 'url', 'https://example.com/'));
console.log(product_images)