javascriptarraysarrayobject

How to verify a key of object exists within a Javascript array of objects?


I have a array like below.

cont arr= [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

Can I know how to verify a 'username' is exist in the array object?


Solution

  • if you want to check if a key exist in all elements of the array you can do this

    const arr= [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
    
    
    
    const existsKey = (data, key) => data.every(d => d.hasOwnProperty(key))
    
    console.log('username', existsKey(arr, 'username'))
    
    console.log('anotherKey', existsKey(arr, 'anotherKey'))