简体   繁体   English

在对象数组中查找所有匹配的 id

[英]Find all matching ids in an array of objects

We have two arrays of objects:我们有两个对象数组:

First:第一的:

const allUsers = [
  {
    id: 49,
    name: 'William'
  },
  {
    id: 82,
    name: 'Michael'
  },
]

Second:第二:

const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
]

[QUESTION]: [题]:

How can I return an array of all the users that were INACTIVE for the last 3 months?如何返回过去 3 个月处于非活动状态的所有用户的数组? (William's) (威廉的)

you can try something你可以试试

function monthDiff(dateFrom, dateTo) {
 return dateTo.getMonth() - dateFrom.getMonth() + 
   (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}

const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
]

const res = usersWithActivity.filter(user => (monthDiff( new Date(user.last_activity),new Date()) > 3))

Try this尝试这个

 const allUsers = [ { id: 49, name: 'William' }, { id: 82, name: 'Michael' }, ]; const usersWithActivity = [ { id: 49, name: 'William', last_activity: "2019-06-20T12:09:55.000Z" }, { id: 82, name: 'Michael', last_activity: "2020-02-20T11:08:50.000Z" } ]; function isInactiveSince(lastActivity, inactiveSince) { let la = new Date(lastActivity); let s = new Date().setMonth(inactiveSince) return la <= s } function play () { const all = []; usersWithActivity.map((ua, i) => { if(isInactiveSince(ua.last_activity, -3)) { const user = allUsers.find(u => u.id == ua.id) all.push(user); } }) console.log(all) } play()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM