'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
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 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mplungjan |
