RXJS,添加新的key:value到嵌套的可观察对象



我是rxjs的新手,我看不出我怎么能做我需要的。我需要递归地添加一对active:true。

我有这个数据结构来自api作为observable:

var data = [
{
name: "hom",
subcategories: [
{ name: "reb" },
{ name: "nov" },
{ name: "otr" }
]
},
{
name: "muj",
subcategories: [
{ name: "REB" },
{ name: "NOV" },
{ name: "OT" }
]
},
{
name: "ni",
subcategories: [
{ name: "REB", subcategories: [
{name: "rebanis"},
{name: "rebawos"}] },
{ name: "NOV", subcategories: [
{name: "novebanis"},
{name: "novrebawos"}] },
{ name: "OT", subcategories: [
{name: "otrebanis"},
{name: "otrebawos"}] 
}
]
}
];

我想要的是在每个有子类别的层上添加一个active:true,我不知道可以有多少个嵌套的子类别。

这是我想要的结果:

var data = [
{
active: true,
name: "hom",
subcategories: [
{ name: "reb" },
{ name: "nov" },
{ name: "otr" }
]
},
{
active: true,
name: "muj",
subcategories: [
{ name: "REB" },
{ name: "NOV" },
{ name: "OT" }
]
},
{
name: "ni",
active: true,
subcategories: [
{ name: "REB", active: true, subcategories: [
{name: "rebanis"},
{name: "rebawos"}] },
{ name: "NOV", active: true, subcategories: [
{name: "novebanis"},
{name: "novrebawos"}] },
{ name: "OT", active: true, subcategories: [
{name: "otrebanis"},
{name: "otrebawos"}] 
}
]
}
];

我试过这样做:

const req = of(data)
.pipe(
map(data => {
const transformedData = Object.keys(data).map(key =>
Object.assign(data[key], { active: true })
);
return transformedData;
})
)
.subscribe(output => console.log(output));

但是结果不清楚,它只影响第一层而不影响嵌套。

可以在递归函数内部使用map:

const data = [ { name: "hom", subcategories: [ { name: "reb" }, { name: "nov" }, { name: "otr" } ] }, { name: "muj", subcategories: [ { name: "REB" }, { name: "NOV" }, { name: "OT" } ] }, { name: "ni", subcategories: [ { name: "REB", subcategories: [ {name: "rebanis"}, {name: "rebawos"}] }, { name: "NOV", subcategories: [ {name: "novebanis"}, {name: "novrebawos"}] }, { name: "OT", subcategories: [ {name: "otrebanis"}, {name: "otrebawos"}] } ] } ];
const addNewProp=data=>data.map(o=>o.subcategories ? ({...o, active:true, subcategories: addNewProp(o.subcategories)}) : o);
console.log(addNewProp(data));

这个问题与rxJs和Observable无关,它是一个数组的转换问题。

我会尝试这样做

data.map(el => {
if(el.subcategories && el.subcategories.lenght > 0) {
const newEl = {...el};
newEl.active = true;
return newEl;
}
return {...el}
})

注意,这里我使用了某种不可变性,因此我在循环中创建了新的元素。如果在您的情况下不需要这样做,您可以像这样简化代码

data.map(el => {
if(el.subcategories && el.subcategories.lenght > 0) {
el.active = true;
}
return el
})

相关内容

  • 没有找到相关文章

最新更新