Вы можете использовать filter
для фильтрации массива.Используйте every
, чтобы проверить, включает ли все элементы определенную строку.
const usersData = {"usersList":[{"user":"user1","langSpeak":["IND","SPN"]},{"user":"user2","langSpeak":["IND"]},{"user":"user1","langSpeak":["IND","SPN","JPN"]},{"user":"user3","langSpeak":["IND","SPN"]},{"user":"user3"}]}
let userFilter = "user1"; //Assign a variable for filtering user
let langFilter = ["IND", "SPN"]; //Assign a variable for filtering language
let result = usersData.usersList.filter(o => o.user == userFilter && o.langSpeak && langFilter.every(e => o.langSpeak.includes(e)));
let finalResult = { //Contruct the final object
usersList: result
}
console.log(finalResult);
Если вам действительно нужно использовать usersKey и usersValue , вы можете использовать reduce
для суммированияфильтр, как:
const usersData = {"usersList":[{"user":"user1","langSpeak":["IND","SPN"]},{"user":"user2","langSpeak":["IND"]},{"user":"user1","langSpeak":["IND","SPN","JPN"]},{"user":"user3","langSpeak":["IND","SPN"]},{"user":"user3"}]}
let usersKey = ["user", "langSpeak"];
let usersValue = ["user1", "IND", "SPN"];
let filter = usersKey.reduce((c, v, i, a) => {
c[v] = i + 1 === a.length ? usersValue.slice(i) : [usersValue[i]];
return c;
}, {});
let result = usersData.usersList.filter(o => Object.entries(filter).every(([k, v]) => v.every(x => o[k].includes(x))));
let finalResult = {
usersList: result
}
console.log(finalResult);