Here is an array written in Typescript:
[
{ "size": "100.34 KB", "name": "Phone.jpg", "documentoContentType": "image/jpeg", "type": "object" },
{ "size": "606.34 KB", "name": "Tulips.jpg", "documentoContentType": "image/jpeg", "type": "flower" },
{ "size": "500.00 KB", "name": "Penguins.jpg", "documentoContentType": "image/jpeg", "type": "animal" }, ...
]
The rule for this array is that you can only have one element of each type, meaning there won't be duplicates of a certain type such as "animal".
I am looking to replace the entry "Tulips.jpg" with a new element called "Cactus.jpg" while keeping the other elements intact:
[
{ "size": "100.34 KB", "name": "Phone.jpg", "documentoContentType": "image/jpeg", "type": "object" },
{ "size": "900.00 KB", "name": "Cactus.jpg", "documentoContentType": "image/jpeg", "type": "flower" },
{ "size": "500.00 KB", "name": "Penguins.jpg", "documentoContentType": "image/jpeg", "type": "animal" }, ...
]
I attempted filtering the array to select only the "flower" type and then replacing it with the new element using splice. However, this method didn't work as expected. How can I achieve this?
let newElement = {
"size": "900.00 KB",
"name": "Cactus.jpg",
"documentoContentType": "image/jpeg",
"type": "flower"
}
let array = [
{ "size": "100.34 KB", "name": "Phone.jpg", "documentoContentType": "image/jpeg", "type": "object" },
{ "size": "606.34 KB", "name": "Tulips.jpg", "documentoContentType": "image/jpeg", "type": "flower" },
{ "size": "500.00 KB", "name": "Penguins.jpg", "documentoContentType": "image/jpeg", "type": "animal" }
]
console.log(array
.filter(item => item.type === "flower")
.splice(0, array.length, newElement)
)
console.log(array)