1

I have a array below that is constantly changing. It is being using in a node.js app. I have everything working good that updates elements of the array but if I restart node and the browser is still running, the webpage still sends data and causes it to crash, so I need to check if array exists before it tries to do something.

My array is like this, called users :-

[ { username: 'a',
    active: true,
    lat: '52.4099584',
    lng: '-1.5310848' } ]

So I need to check username 'a' exists. I have tried

users.map(obj => obj.username).indexOf(value) >= 0;

but doesnt work?

Any suggestions?

Thanks

6
  • 3
    users.some( obj => obj.username === 'a' )? Commented Nov 24, 2018 at 21:48
  • It was on here somewhere, supposed to give a true or false if exists Commented Nov 24, 2018 at 21:49
  • 1
    return users.find(user => user.username === 'a'); or as Thomas wrote. return users.some(user => user.username); Commented Nov 24, 2018 at 21:52
  • 1
    Seems to work fine Commented Nov 24, 2018 at 21:56
  • Wierd, that works great in jsfiddle but I get this error when added to my script result = users.map(obj => obj.username).indexOf(value) >= 0; ^ ReferenceError: value is not defined Commented Nov 24, 2018 at 22:10

1 Answer 1

1

If you're looking to remve the users that don't have a username, then you could do something like this.

const data = [{ 
    username: 'a',
    active: true,
    lat: '52.4099584',
    lng: '-1.5310848' },
   { 
    username: undefined,
    active: true,
    lat: '52.4099584',
    lng: '-1.5310848' }];
    
    
console.log(data.filter(({username})=> username && username !== null));

Otherwise, you should just use something like every

const data = [ { 
    username: undefined,
    active: true,
    lat: '52.4099584',
    lng: '-1.5310848' },
    { 
    username: 'a',
    active: true,
    lat: '52.4099584',
    lng: '-1.5310848' }];


console.log(data.every(({username})=> username && username !== null));

Or findIndex

const data = [ { 
        username: undefined,
        active: true,
        lat: '52.4099584',
        lng: '-1.5310848' },
        { 
        username: 'a',
        active: true,
        lat: '52.4099584',
        lng: '-1.5310848' }];


    console.log(data.findIndex(({username})=> !username || username === null) > -1);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.