我有以下資料:
const section={
fileds: [
{
child: [
{
fileds: [
{
id: "kxf5",
label: null
}
]
},
{
fileds: [
{
id: "ed5t",
label: "section"
}
]
},
]
},
{
child: [
{
fileds: [
{
id: "ccfr",
label: null
}
]
},
{
fileds: [
{
id: "kdpt8",
label: "section"
}
]
},
]
},
]
}
我需要在陣列中回傳所有id,我應該使用遞回。
我嘗試了以下代碼。
const section={fileds: [{child: [{fileds: [{id: "kxf5",label: null}]},{fileds: [{id: "ed5t",label: "section"}]},]},{child: [{fileds: [{id: "ccfr",label: null}]},{fileds: [{id: "kdpt8",label: "section"}]},]},]}
function printId(value, child ) {
return [value, ...(child ? printList(child) : [])]
}
console.log(printId(section.fields));
但這對我沒有幫助。
有沒有辦法用遞回解決這個問題?請幫助解決這個問題。
最后的結果應該是這樣的["kxf5","ed5t","ccfr", "kdpt8"]。
uj5u.com熱心網友回復:
一個更好的解決方案可能是這個:
// recursive method to extract "id"s
function getId(o) {
// if current parameter "o" has "id" prop, return it
if (o.id) return o.id;
// else, iterate over "o" and recurse for each "value" of "o"
return Object.keys(o).flatMap((key) => getId(o[key]));
}
const section = {
fileds: [{
child: [{
fileds: [{
id: "kxf5",
label: null
}]
},
{
fileds: [{
id: "ed5t",
label: "section"
}]
},
]
},
{
child: [{
fileds: [{
id: "ccfr",
label: null
}]
},
{
fileds: [{
id: "kdpt8",
label: "section"
}]
},
]
},
]
};
console.log(getId(section));
uj5u.com熱心網友回復:
以下是實作目標的一種可能方式。
代碼片段
// recursively get only "id"s
const getIds = arr => (
// implicit return of below result
// iterate using ".flatMap()" to avoid nested result
arr.flatMap(obj => {
// extract values that are arrays
const arrArrs = Object.values(obj).filter(v => Array.isArray(v));
// extract values for key "id"
const arrVals = Object.entries(obj).filter(
([k, v]) => typeof v === 'string' && k === "id"
).map(([k, v]) => v);
// return "id" values, and then recursively call getIds for each "ar" (array)
return [...arrVals, ...arrArrs.flatMap(ar => getIds(ar))]
})
);
const section = {
fileds: [{
child: [{
fileds: [{
id: "kxf5",
label: null
}]
},
{
fileds: [{
id: "ed5t",
label: "section"
}]
},
]
},
{
child: [{
fileds: [{
id: "ccfr",
label: null
}]
},
{
fileds: [{
id: "kdpt8",
label: "section"
}]
},
]
},
]
};
console.log(getIds(section.fileds));
解釋
在上面的代碼段中添加了行內注釋。
uj5u.com熱心網友回復:
另一種方式,reduce()用于遞回填充陣列
const section= {fileds: [{child: [{fileds: [{id: "kxf5", label: null } ] }, {fileds: [{id: "ed5t", label: "section"} ] }, ] }, {child: [{fileds: [{id: "ccfr", label: null } ] }, {fileds: [{id: "kdpt8", label: "section"} ] }, ] }, ] }
function printId(value) {
return value.reduce((prev, cur) => {
if (cur.id) {
return [ ...prev, cur.id ];
} else {
let key = ('child' in cur) ? 'child' : 'fileds';
return [ ...prev, ...printId(cur[key]) ]
}
}, []);
}
console.log(printId(section.fileds));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464696.html
標籤:javascript
