【问题标题】:Lodash check if any object in array contains id match from another arrayLodash 检查数组中的任何对象是否包含来自另一个数组的 id 匹配项
【发布时间】:2018-01-17 04:52:23
【问题描述】:

我有一个用户数组,例如:

var users = [{
 id: 1,
 name: 'ABC',
 isDisplay: true
}, {
 id: 2,
 name: 'XYZ',
 isDisplay: true
}, {
 id: 3,
 name: 'JKL',
 isDisplay: true
}];

另一个数组 selectedUsers 包含上面数组中的一些对象,例如:

var selectedUsers = [{
 id: 1,
  name: 'ABC'
 },
 {
  id: 3,
  name: 'JKL'
}];

不使用 lodash,我想通过匹配其 ID 来识别第二个数组中存在的对象。

 _.each(users, (_u) => {
     if(selectedUsers.includes(_u)) {
       _u.isDisplay = false;
     } else {
       _u.isDisplay = true;
     }
  });

我尝试将整个对象与includes 匹配,但它不起作用,因为我使用的是 angularjs,所以 angular 将一些 $$hashkey 与对象相匹配,所以它不会匹配,有没有其他方法可以做到这一点。

【问题讨论】:

  • 不带 lodash:users.forEach(u => u.isDisplay = selectedUsers.some(su => su.id === u.id)).
  • 你只需要过滤数组。
  • @Ved 如果 id 存在于 selecteduser 中,我需要将用户的 isDisplay 设置为 false。
  • @Tushar users.forEach(u => u.isDisplay = !selectedUsers.some(su => su.id === u.id)).. 这对我有用。,刚刚添加!在赋值之前。谢谢

标签: javascript angularjs lodash


【解决方案1】:

var users = [{
 id: 1,
 name: 'ABC',
 isDisplay: true
}, {
 id: 2,
 name: 'XYZ',
 isDisplay: true
}, {
 id: 3,
 name: 'JKL',
 isDisplay: true
}];

var selectedUsers = [{
 id: 1,
  name: 'ABC'
 },
 {
  id: 3,
  name: 'JKL'
}];

var intersection = _.intersectionBy(users, selectedUsers, 'id');

console.log(intersection);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>

【讨论】:

    【解决方案2】:

    创建一个具有选定 ID (selectedUsersIds) 的 Set。使用Array#forEach 迭代users 数组,通过检查id 是否存在于selectedUsersIds 集合中来分配isDisplay 的值:

    const users = [{"id":1,"name":"ABC","isDisplay":true},{"id":2,"name":"XYZ","isDisplay":true},{"id":3,"name":"JKL","isDisplay":true}];
    
    const selectedUsers = [{"id":1,"name":"ABC"},{"id":3,"name":"JKL"}];
    
    const selectedUsersIds = new Set(selectedUsers.map(({ id }) => id));
    
    users.forEach((u) => u.isDisplay = selectedUsersIds.has(u.id));
    
    console.log(users);

    【讨论】:

      猜你喜欢
      • 2011-01-16
      • 2016-04-24
      • 1970-01-01
      • 2021-05-15
      • 2019-07-26
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多