[英]How to extract all possible matching arrays of objects from one array of objects?
[英]how to extract all objects from nested arrays into one array in React
我有一個這樣的數組,這是我的useState
的初始狀態:
Array [ (6) […], (6) […] ]
0: Array(6) [ undefined, {…}, {…}, … ]
1: Array(6) [ undefined, undefined, {…}, … ]
例如:
const[arr,setArr] = React.useState([
[
{label: "Beklam", id: 5032},
{label: "Dx6", id: 5052},
undefined,
undefined
],
[
{label: "item1", id: 50567},
{label: "item4", id: 505567},
{label: "item6", id: 50537},
{label: "itemA", id: 505647},
undefined,
undefined,
]
])
我想這樣做:
[
{label: "Beklam", id: 5032},
{label: "Dx6", id: 5052},
{label: "item1", id: 50567},
{label: "item4", id: 505567},
{label: "item6", id: 50537},
{label: "itemA", id: 505647},
]
我應該提到undefined
的值來自輸入。 就我而言,可能會收到undefined
的消息,我應該處理它。
這是來自瀏覽器的console.log
輸出。 有一個數組,里面有兩個數組。 這兩個數組中的每一個都有 6 個元素。 它們可以超過 6 個。因此元素的數量不是靜態的,數組也是如此。
該數組可以有多個子數組。
是這樣的:
0: undefined
1: undefined
2: Object { label: "Beklam", id: 5032 }
3: Object { label: "0/65%", id: 5061 }
4: undefined
5: undefined
我想將子數組中的所有對象提取到一個對象中。 顯然是將這兩個數組的所有值提取到一個包含它們的對象的數組中。
如果可能,過濾undefined
的值而不顯示它們。 而不是稍后嘗試在變量上使用array.filter
。
我其實沒有遇到過這樣的問題。 所以我真的不知道如何處理多維數組。
您可以只使用平面圖將其制成一維數組。
console.log(arr.flatMap((e) => e));
或者更簡單:
console.log(arr.flat());
並過濾掉未定義的值:
console.log(arr.flatMap((e) => e.filter((f) => f !== undefined)));
另一個使用數組基本函數的例子,比如filter()
和concat()
:
var arr = [ [ {label: "Beklam", id: 5032}, {label: "Dx6", id: 5052}, undefined, undefined ], [ {label: "item1", id: 50567}, {label: "item4", id: 505567}, {label: "item6", id: 50537}, {label: "itemA", id: 505647}, undefined, undefined, ] ]; arr = arr[0].concat(arr[1]); var arr2 = arr.filter(e => e;= undefined && e). console.log(arr2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.