Home > OS >  How to pass data from object into new array in javascript?
How to pass data from object into new array in javascript?

Time:12-12

I want to send only one of the fields contained in the data object var arrImg. The first thing I want to push is an image field of var arrImg with a condition where checked is true into the new array image on crudData:{'image':[]}. Then the second I want to push the field name of var arrImg with a condition where checked is true into a new array name on crudData:{'name':[]}. Checked value is set to false first, but will change to true when the input checkbox is clicked. Does someone understand for the case I'm asking? i'm new to javascript. Thanks.

Here's myfiddle https://jsfiddle.net/Annisa_Lianda30/d0ber5Lu/24/

This is my code:

<script>
export default {
    data() {
        return{
            crudData:{
                'id': null,
                'name': [],
                'image': [],
                'arrImage': [],
            },
        }
    },

    propertyImageUpload(e, maxItem){                    
            let input = this.$refs.uploadProperty
            let file = input.files
            if(file.length > (maxItem - this.crudData.arrImage.length)){
                $('#uploadMultiFile').val('')
                alert('You can only upload max ' maxItem ' items')
            } else {
                for(let i = 0; i < file.length; i  ){
                    var valueArr = this.crudData.arrImage.map(function(item){ return item.fileName })
                    var isDuplicate = valueArr.some(function(item, idx){ 
                        return item == file[i].name 
                    })
                    if (isDuplicate) {
                        alert("You've already uploaded this file")
                        continue
                    }else{
                        var arrImg = {
                            blob: URL.createObjectURL(file[i]),
                            image: file[i],
                            fileName: file[i].name,
                            checked: false,
                            name : null
                        }
                        this.crudData.arrImage.push(arrImg)
                        console.log(this.crudData.arrImage)
                    }
                }
            }
        },
        uploadImageProperty(e){
            this.$refs.uploadProperty.click()
        },
        removeProperty(key){
            this.crudData.arrImage.splice(key, 1)
        }, 

}

This is the output i got from crudData.arrImage: Output Javascript

CodePudding user response:

Welcome to SO. Hopefully this code snippet can help guide you towards what your looking for.

let checkedImages = this.crudData.arrImage.filter(img => img.checked)
let imageFiles = checkedImages.map(img => img.image)
let names = checkedImages.map(img => img.fileName)
console.log({ imageFiles,names })
  • Related