[英]Javascript check if string exists in array of objects
我的程序中有兩個數組,一個包含作為鍵的字符串列表,另一個包含包含鍵的對象。
let classKeys = ['math', 'robotics'];
let classesInList = [{key : "WIHUGDYVWJ", className : 'math'},{key : "qwljdhkuqwdnqwdk", className : 'english'},{key : "likubqwd", className : 'robotics'},];
我只需要在classKeys中存在鍵(作為className屬性)時才返回另一個包含classesInList等對象的數組
例如,在這種情況下,我需要針對classesInList檢查classKeys並創建一個包含兩個項的數組:
[{key : "WIHUGDYVWJ", className : 'math'},{key : "likubqwd", className : 'robotics'}]
因為英語不在classKeys中,所以它從classesInList中刪除。 我該怎么做?
側注:我使用的是本機反應,因此我可以訪問es6屬性和函數。
我完全陷入了這種意義上。 無論這看起來多么簡單,我都找不到答案。
只需使用Array.prototype.filter
並將其與Array.prototype.includes
結合使用。 你想要做的是過濾對象的classesInList
數組,並只選擇那些className
值存在於classKeys
數組中的classKeys
。
let classKeys = ['math', 'robotics']; let classesInList = [{key : "WIHUGDYVWJ", className : 'math'},{key : "qwljdhkuqwdnqwdk", className : 'english'},{key : "likubqwd", className : 'robotics'}]; let filteredClasses = classesInList.filter(cls => classKeys.includes(cls.className)); console.log(filteredClasses);
您可以使用filter
數組方法並檢查元素的className
是否在classKeys
數組中:
let classKeys = ["math", "robotics"]; let classesInList = [ { key: "WIHUGDYVWJ", className: "math" }, { key: "qwljdhkuqwdnqwdk", className: "english" }, { key: "likubqwd", className: "robotics" } ]; let result = classesInList.filter(element => { return classKeys.indexOf(element.className) !== -1; }); console.log(result);
使用filter
將過濾您的數組,使用some
來獲取您的標准是否真的有些值,最后使用includes
來檢查該值是否包含在您的classKeys中。
let classKeys = ['math', 'robotics']; let classesInList = [{key : "WIHUGDYVWJ", className : 'math'},{key : "qwljdhkuqwdnqwdk", className : 'english'},{key : "likubqwd", className : 'robotics'},]; const result = classesInList .filter(c => Object.values(c).some(val => classKeys.includes(val) ) ); console.log(result);
使用與Array.prototype.filter
和Array.prototype.includes
解構:
let classKeys = ['math', 'robotics']; let classesInList = [{key : "WIHUGDYVWJ", className : 'math'},{key : "qwljdhkuqwdnqwdk", className : 'english'},{key : "likubqwd", className : 'robotics'}]; let filtered = classesInList.filter(({ className }) => classKeys.includes(className)); console.log(filtered);
您可以使用filter
, includes
和object destructuring在ES6中執行此操作:
const classKeys = ['math', 'robotics']; const classesInList = [{key : "WIHUGDYVWJ", className : 'math'},{key : "qwljdhkuqwdnqwdk", className : 'english'},{key : "likubqwd", className : 'robotics'},]; const result = classesInList.filter(({ className }) => classKeys.includes(className)); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.