Home > Software design >  Filtering object by value of other key JavaScript
Filtering object by value of other key JavaScript

Time:11-10

I have object like this : `

let data = {
        approval: [
            {
                name: 'XXXX',
                kode: '10'
            },
            {
                name: 'YYYY',
                kode: '12'
            },
            {
                name: 'ZZZZ',
                kode: '14'
            },
            {
                name: 'HHHH',
                kode: '09'
            }
            
        ],
        batas: "10"
    }

` i want to display the data that equal to this condition (kode >= 10) so if the 'kode' is less than 'batas' it shouldn't appears, any help?

So in that case the output should be like this `

approval: [
            {
                name: 'XXXX',
                kode: '10'
            },
            {
                name: 'YYYY',
                kode: '12'
            },
            {
                name: 'ZZZZ',
                kode: '14'
            }
            
        ]

` the data is come from ajax, Thanks for your help..

CodePudding user response:

I made the es6 javascript code.

First I put the approval array and batas into the variable first.

Then I use for loop iteration to find data less than 10, then I delete it using splice.

The last time I returned it was an object

This is my code :

    const batas = (data) => {
        let arr = data.approval
        let batas = data.batas
        for (let i = 0; i < arr.length; i  ) {
            if (arr[i]['kode'] < batas) arr.splice(i, 1)
        }
        return data
    }
    
    let data = {
        approval: [
            {
                name: 'XXXX',
                kode: '10'
            },
            {
                name: 'YYYY',
                kode: '12'
            },
            {
                name: 'ZZZZ',
                kode: '14'
            },
            {
                name: 'HHHH',
                kode: '09'
            }
        ],
        batas: '10'
    }
    
    console.log(batas(data))

CodePudding user response:

Using filter method can do this, for more info check: MDN - filter.

let data = {
        approval: [
            {
                name: 'XXXX',
                kode: '10'
            },
            {
                name: 'YYYY',
                kode: '12'
            },
            {
                name: 'ZZZZ',
                kode: '14'
            },
            {
                name: 'HHHH',
                kode: '09'
            }
            
        ],
        batas: "10"
    }

const filteredData = {approval: data.approval.filter(item => item.kode >= data.batas)}

console.log('filteredData: ', filteredData)

  • Related