-1

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?

Madush Nim
  • 41
  • 4
  • or [return true if all objects in array has value in property](https://stackoverflow.com/questions/36148546/return-true-if-all-objects-in-array-has-value-in-property) or [Checking an array if all objects inside contains a given key value(javascript)](https://stackoverflow.com/questions/68857827/checking-an-array-if-all-objects-inside-contains-a-given-key-valuejavascript) if looking for specific value – pilchard Nov 21 '22 at 09:00

1 Answers1

0

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'))
R4ncid
  • 6,944
  • 1
  • 4
  • 18