Как найти первый элемент в массиве и если он пустой то вставить или удалить?
Как при загрузке проверить, если в массиве product.thumbs есть пустой элемент (первый найденный) с image === '' то в него вставить данные, если в массиве нет пустых значений то просто запушить в массив
сам массив
product: {
thumbs: [
{
image: '',
thumb: '',
},
{
image: '',
thumb: '',
},
{
image: '',
thumb: '',
},
{
image: '',
thumb: '',
},
],
}
и функция загрузки
uploadGallery() {
const that = this
const galleries = event.target.files
galleries.forEach(function (value, index, product) {
const formData = new FormData()
formData.append('image', value)
formData.append('path', 'products')
that.$axios
.$post('/api/v1/shop/1/upload/image', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then((response) => {
if (!that.product.image) {
that.product.image = response.path + response.image
}
that.product.thumbs.push({
image: response.image,
path: response.path,
})
})
.catch((error) => {
})
return index < that.countThumb + 1
})
},
Ответы (2 шт):
Автор решения: Aziz Umarov
→ Ссылка
Как-то так
let product = {
thumbs: [
{
image: '',
thumb: '',
},
{
image: '',
thumb: '',
},
{
image: '',
thumb: '',
},
{
image: '',
thumb: '',
}
]
}
if (product.thumbs.find(item => item.image === "") != null) {
product.thumbs.find(item => item.image === "").image = "response.path " + "response.image"
}
product.thumbs.push({
image: "response.image",
path: "response.path"
})
console.log(product)
Автор решения: Серега Мангышев
→ Ссылка
Можно сделать через функцию. Так можно получить не только image, но и любой указанный key.
let product = {
thumbs: [
{
image: 'Не пустой image',
thumb: '2',
},
{
image: 'Не пустой image',
thumb: '4',
},
{
image: 'Не пустой image',
thumb: '',
},
{
image: '',
thumb: '',
}
]
}
function findEmptyValue(arr, key) {
return arr.map(el => el[key].length === 0 ? 'image' : el);
}
console.log(findEmptyValue(product.thumbs, 'image'));