0

I'm attempting to check if a user's ID is in this array and if they are, also get the "text" from it.

Array:

const staff = [
    {
        user: '245569534218469376',
        text: 'dev'
    },
    {
        user: '294597887919128576',
        text: 'loner'
    }
];

I've tried if (staff.user.includes(msg.member.id)) (Which I didn't think was going to work, and didn't.)

The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • You are missing a language tag. If JavaScript: try something like `const match = array.find(value => value.user === msg.member.id);` – pzaenger Jul 06 '20 at 22:45
  • I just tried: `const match = staff.find(value => value.user === msg.member.id) bot.createMessage(msg.channel.id,match.toString())` - Returns [object Object] - Unsure what I need to add. –  Jul 06 '20 at 22:55
  • includes only works well for value objects such as strings and numbers, for reference objects it will only match if you have a reference to the object you are testing for. Use the some method instead. – Adrian Brand Jul 06 '20 at 23:02

4 Answers4

0

const findUser = (users, id) => users.find(user => user.id === id)

const usersExample = [
  {
    id: '123456765',
    text: 'sdfsdfsdsd'
  },
  {
    id: '654345676',
    text: 'fdgdgdg'
  }
]
//////////////////


const user = findUser(usersExample, '123456765')

console.log(user && user.text)
kerm
  • 653
  • 1
  • 5
  • 15
0

The some method on an array is used to tell if an item meets a condition, it is similar to the find method but the find method returns the item where the some method return true or false.

const staff = [
    {
        user: '245569534218469376',
        text: 'dev'
    },
    {
        user: '294597887919128576',
        text: 'loner'
    }
];

const isStaff = (staff, id) => staff.some(s => s.user === id);

console.log(isStaff(staff, '123'));

console.log(isStaff(staff, '245569534218469376'));
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
0

You may try something like this:

const staff = [
    {
        user: '245569534218469376',
        text: 'dev'
    },
    {
        user: '294597887919128576',
        text: 'loner'
    }
];

let item = staff.find(item => item.user == '294597887919128576'); // msg.member.id

if (item) {
    console.log(item.text);
}
The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

One another way to do that is:

const inArray = (array, id) => array.filter(item => item.user === id).length >= 1;

const users = [
{
  user: '245569534218469356',
  text: 'foo'
  }, {
  user: '245564734218469376',
  text: 'bar'
  }, {
  user: '246869534218469376',
  text: 'baz'
  }
];


console.log(inArray(users, '246869534218469376'));  // true 
console.log(inArray(users, '222479534218469376'));  // false