[英]Lodash check if any object in array contains id match from another array
I have one user array like: 我有一个用户数组,如:
var users = [{
id: 1,
name: 'ABC',
isDisplay: true
}, {
id: 2,
name: 'XYZ',
isDisplay: true
}, {
id: 3,
name: 'JKL',
isDisplay: true
}];
And another array selectedUsers which contains some object from above array like: 另一个数组selectedUsers包含上面数组中的一些对象,例如:
var selectedUsers = [{
id: 1,
name: 'ABC'
},
{
id: 3,
name: 'JKL'
}];
Not with lodash, i want to indentify which object are present in second array with matching its ID
. 与lodash无关,我想确定第二个数组中存在哪些对象及其
ID
匹配。
_.each(users, (_u) => {
if(selectedUsers.includes(_u)) {
_u.isDisplay = false;
} else {
_u.isDisplay = true;
}
});
I have tried to match whole object with includes
but it dint work, because i am using angularjs, so angular put some $$hashkey with object, so it will not match, Is there any other way to do this. 我试图将整个对象与
includes
匹配,但是它确实可以工作,因为我使用的是angularjs,所以angular将一些$$ hashkey与object匹配,所以它将不匹配,还有其他方法可以做到这一点。
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>
Create a Set of selected ids ( selectedUsersIds
). 创建一组选定的ID(
selectedUsersIds
)。 Iterate the users
array with Array#forEach , assign the value of isDisplay
by checking if the id
exists in the 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.