[英]Accessing all Individual Values of a Nested Object Array?
我正在嘗試訪問每個項目的每個列表對象的單獨計數值以在數組中使用它們。 我嘗試了各種地圖方法,但它一直返回未定義。 我需要一種動態方法來收集這些計數,以便在添加更多列表、項目、位置和計數時,它會更新。
數據:
const data = [
{
name: "List1",
items: [
{
name: "Item1",
locations: [
{ position: "a", count: 20 },
{ position: "b", count: 30 },
],
},
{
name: "Item2",
locations: [
{ position: "c", count: 40 },
{ position: "d", count: 50 },
],
},
],
},
{
name: "List2",
items: [
{
name: "Item3",
locations: [
{ position: "e", count: 60 },
{ position: "f", count: 70 },
],
},
{
name: "Item4",
locations: [
{ position: "g", count: 80 },
{ position: "h", count: 90 },
],
},
],
},
];
預期結果:
const onlyCounts = [20,30,40,50,60,70,80,90];
任何提示或信息將不勝感激,謝謝!
如果您因為不確定嵌套對象的形狀/鍵/深度而需要通用解決方案,這里有一個遞歸解決方案,只要您的數據沒有任何循環,它就可以工作。
const getCounts = (value) =>
value.flatMap((el) =>
Object.entries(el).flatMap(([key, value]) => {
if (key === "count") return [value];
if (Array.isArray(value)) return getCounts(value);
return [];
})
);
const data = [ { name: "List1", items: [ { name: "Item1", locations: [ { position: "a", count: 20 }, { position: "b", count: 30 } ] }, { name: "Item2", locations: [ { position: "c", count: 40 }, { position: "d", count: 50 } ] } ] }, { name: "List2", items: [ { name: "Item3", locations: [ { position: "e", count: 60 }, { position: "f", count: 70 } ] }, { name: "Item4", locations: [ { position: "g", count: 80 }, { position: "h", count: 90 } ] } ] } ]; const getCounts = (value) => value.flatMap((el) => Object.entries(el).flatMap(([key, value]) => { if (key === "count") return [value]; if (Array.isArray(value)) return getCounts(value); return []; }) ); console.log(getCounts(data))
真正通用的解決方案
const getFieldArray = (value, field) =>
value.flatMap((el) =>
Object.entries(el).flatMap(([key, value]) => {
if (key === field) return [value];
if (Array.isArray(value)) return getFieldArray(value, field);
return [];
})
);
console.log(getFieldArray(data, 'count'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.