Typescript 从嵌套对象中获取 属性 的所有值
Typescript get all values of a property from a nested object
我有一个嵌套对象:
{
id: 240,
name: 'FY1 2022',
children: [
{
id: 241,
name: 'Q1 2022',
children: [
{
id: 242,
name: 'Jan 2022',
},
{
id: 243,
name: 'Feb 2022',
},
{
id: 244,
name: 'Mar 2022',
},
],
},
],
};
我需要将所有 id 值从没有 属性 children
.
的对象中获取到一个数组中
有办法吗?
提前致谢!
你可以试试这个:
type MyObject = {
id: number,
name: string,
children?: MyObject[]
}
function getIds(obj: MyObject): number[] {
if (!obj.children) {
return [obj.id];
}
return obj.children.reduce((ids:number[],o: MyObject)=> {
ids.push(...getIds(o))
return ids
},[]);
}
试试这个(使用递归)
const test = {
id: 240,
name: 'FY1 2022',
children: [
{
id: 241,
name: 'Q1 2022',
children: [
{
id: 242,
name: 'Jan 2022',
},
{
id: 243,
name: 'Feb 2022',
},
{
id: 244,
name: 'Mar 2022',
},
],
},
],
};
function addToArray(array, obj) {
if (obj.children) {
obj.children.forEach(child => addToArray(array, child))
} else {
array.push(obj.id)
}
return array
}
const array = []
console.log(addToArray(array, test))
我有一个嵌套对象:
{
id: 240,
name: 'FY1 2022',
children: [
{
id: 241,
name: 'Q1 2022',
children: [
{
id: 242,
name: 'Jan 2022',
},
{
id: 243,
name: 'Feb 2022',
},
{
id: 244,
name: 'Mar 2022',
},
],
},
],
};
我需要将所有 id 值从没有 属性 children
.
有办法吗?
提前致谢!
你可以试试这个:
type MyObject = {
id: number,
name: string,
children?: MyObject[]
}
function getIds(obj: MyObject): number[] {
if (!obj.children) {
return [obj.id];
}
return obj.children.reduce((ids:number[],o: MyObject)=> {
ids.push(...getIds(o))
return ids
},[]);
}
试试这个(使用递归)
const test = {
id: 240,
name: 'FY1 2022',
children: [
{
id: 241,
name: 'Q1 2022',
children: [
{
id: 242,
name: 'Jan 2022',
},
{
id: 243,
name: 'Feb 2022',
},
{
id: 244,
name: 'Mar 2022',
},
],
},
],
};
function addToArray(array, obj) {
if (obj.children) {
obj.children.forEach(child => addToArray(array, child))
} else {
array.push(obj.id)
}
return array
}
const array = []
console.log(addToArray(array, test))