Answer the question
In order to leave comments, you need to log in
How to find a user who has objects with the same id in the array of objects?
There is a user
{
id: 1,
items: [{
id: 124,
price: 1
},{
id: 31
price: 1
},{
id: 32,
price: 1
}]
}
ids = [32, 124]
Answer the question
In order to leave comments, you need to log in
https://docs.mongodb.com/manual/reference/operator...
try
User.findOne({ 'items.id': { $all: ids } })
var users = [
{
id: 1,
items: [
{ id: 124, price: 1 },{ id: 31, price: 1 },{ id: 32, price: 1 },
],
},
{
id: 2,
items: [
{ id: 345, price: 1 },{ id: 2, price: 1 },{ id: 166, price: 1 },
],
},
];
function usersFindOne(itemsArr) {
return users.find(u => {
return u.items.every(item => itemsArr.includes(item.id));
});
};
console.log(usersFindOne([124, 32, 31]));
console.log(usersFindOne([345, 111, 166, 2]));
I just don’t know how best to do it right away when requesting it, or already cycle through the resulting array
let obj = {
id: 1,
items: [{
id: 124,
price: 1
}, {
id: 31,
price: 1
}, {
id: 32,
price: 1
}]
};
let arr = [];
let ids = [32, 31, 124]
for (let i = 0; i < Object.keys(obj.items).length; i++) {
for (let key in obj.items) {
arr.push(obj.items[i].id)
}
}
let unique = new Set(arr)
let new_arr = [...unique]
let coincidences = 0;
for (let i = 0; i < ids.length; i++) {
if (ids.includes(new_arr[i])) coincidences++
}
if (coincidences === new_arr.length) {
alert("У пользователя в items есть все элементы из массива ids")
} else {
alert("У пользователя в items нету всех элементов из массива ids")
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question