0

我正在尝试检查用户的 ID 是否在此数组中,如果是,也从中获取“文本”。

大批:

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

我试过if (staff.user.includes(msg.member.id))了(我认为这不会奏效,也没有。)

4

4 回答 4

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)

于 2020-07-06T22:54:35.570 回答
0

数组上的 some 方法用于判断一个项目是否满足条件,它类似于 find 方法,但 find 方法返回 some 方法返回 true 或 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'));

于 2020-07-06T22:58:52.550 回答
0

你可以尝试这样的事情:

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);
}

于 2020-07-06T23:08:40.787 回答
0

另一种方法是:

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
于 2020-07-06T23:17:26.930 回答