![](/img/trans.png)
[英]Check if a nested array contains any element of another nested array in JavaScript
[英]Check if an array contains any element of another array with some null in JavaScript
我有一個目標數組示例: ["Potato", "Orange"]
。 我正在進行api調用,該調用返回具有多個數組的對象,如果數組包含任何目標數組元素,則必須查看該對象。
我有以下代碼,但是出現以下錯誤:Uncaught TypeError:無法讀取null的屬性“ includes”
我知道這是因為對象包含一些Null值。 我怎樣才能解決這個問題?
Example: const myArray = [
{
Track: ["Potato", "Apple"],
["Banna"],
["Potato", "Batman", "Orange"]
Type: ["Some", "Stuff"]
},
{
Track: null
Type: ["Some", "Stuff"]
}
]
const value = "Potato"
const matchingSession = myArray.filter((obj) => value.some(x => { return obj.types.includes(x) || obj.tracks.includes(x)}));
它應該返回:
[
["Potato", "Apple"],
["Potato", "Batman", "Orange"]
]
這只是一個例子。 數組中可能有多個對象。
myArray.filter((arr) => Array.isArray(arr) && arr.length > 0)
此行檢查數組對象是否為數組類型並且不為空
閱讀有關過濾器的更多信息
const arrayOfValues = ["Potato", "Apple"];
myArray.filter((arr) => {
return Array.isArray(arr) && CheckArray(arrayOfValues, arr) && arr.length > 0
});
function CheckArray(Array, ArrayToCheck) {
let found = false;
for (const value of Array) {
if (ArrayToCheck.includes(value)) {
found = true;
}
}
return found;
}
檢查數組是否包含arrayOfValues
之一,以及對象是否為數組而不為空!
const myArray = [
{
Track: ["Potato", "Apple"],
data: [["Banna"],
["Potato", "Batman", "Orange"],
["Some", "Stuff"]],
},
{
Tack: null,
data: ["Some", "Stuff"],
},
];
myArray.map((arr) => {
return Array.isArray(arr.data) && CheckArray(arr.Track, arr.data);
}).filter(_ => !!_);
function CheckArray(arr, ArrayToCheck) {
if (!arr || !Array.isArray(arr)) {
return ArrayToCheck;
}
const foundArray = [];
if (ArrayToCheck.every(item => Array.isArray(item))) {
for (const subArr of ArrayToCheck) {
const ResultArray = CheckArray(arr, subArr);
if (ResultArray.length > 0) {
foundArray.push(ResultArray);
}
}
} else {
if (ArrayToCheck.map(val => arr.includes(val)).includes(true)) {
foundArray.push(ArrayToCheck);
}
}
return foundArray;
}
檢查array
包含Track
數據之一(適用於子數組(2d等)。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.