gpt4 book ai didi

javascript - 如何展平不同对象的嵌套数组但仅从现有属性名称获取值?

转载 作者:行者123 更新时间:2023-12-02 21:15:04 24 4
gpt4 key购买 nike

我想知道如何展平不同对象的嵌套数组并仅从(任何对象的)现有属性名称中获取现有值?

我只想从 2 个不同对象的嵌套数组中获取所有 propertyId 值。

export interface LeftMenuItem {
text: string;
routerUrl?: string;
isExpanded: boolean;
propertyId?: string;
children: LeftMenuChildrenItem[];
}
export interface LeftMenuChildrenItem {
text: string;
routerUrl?. string;
propertyId?: string;
isCustomer: boolean
}

const leftMenuPropertyIds: string[] = [];

this.leftMenuItems.forEach(val1 => {
if (val1.propertyId) {
leftMenuPropertyIds.push(val1.propertyId);
}
if (val1.children.length > 0) {
val1.children.forEach(val2 => {
if (val2.propertyId) {
leftMenuPropertyIds.push(val2.propertyId);
}
});
}
});

console.log(leftMenuPropertyIds);

最佳答案

使用reduce方法压平数组对象。减少将有助于删除不需要的节点。

const list = [
{
propertyId: "1",
text: "1",
children: [
{ propertyId: "2", text: "1", children: [] },
{ propertyId: "", text: "1", children: [] },
{ propertyId: "3", text: "1", children: [] }
]
}
];

const flat = (v, arr) => {
if (v.propertyId) arr.push(v.propertyId);
(v.children || []).forEach(v2 => flat(v2, arr));
return arr;
};
const rest = list.reduce((arr, item) => flat(item, arr), []);

console.log(rest);

关于javascript - 如何展平不同对象的嵌套数组但仅从现有属性名称获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60994374/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com