【发布时间】:2021-01-31 22:19:51
【问题描述】:
我发出两个 GET 请求,第二个(“链接”)的数据依赖于第一个(“类别”)的数据。我的目标是从两者中创建一个新的对象数组,并对分配给它的类别下的链接进行排序。
理想情况下,我希望新的 obj 数组看起来像这样:
return {
"_Category": m.Category, // "Animals"
"_RootID": m.ID, // "1"
"_Child": {
"_Title": "" // {_Title: "Otter"}, {_Title: "Monkey"}, etc
"_Link": "" // "otters.com", etc
}
}
如果做得好,下一个类别分组将是:
"_Category": m.Category, // "Fruit"
"_RootID": m.ID, // "2"
"_Child": {
"_Title": "" // {_Title: "Banana"}, {_Title: "Apple"}, etc
"_Link": "" // "bananas.com", etc
}
等等。
我已经能够加载"_Title" 下的所有链接,但问题是它们没有按类别分隔。它看起来像:
"_Category": m.Category, // "Fruit"
"_RootID": m.ID, // "2"
"_Child": {
"_Title": "" // {_Title: "Otter"}, {_Title: "Banana"}, {_Title: "Monkey"}, etc
"_Link": ""
}
如何根据关联的类别分配第二个数组中的链接?
代码:
const getCategories = `${something}/getByTitle('Some_Categories')/items?$select=ID,Nav_x0020_Group/Title,Category&$expand=Nav_x0020_Group`,
getLinks = `${something}/getByTitle('Some_Links')/items?$select=ID,Title,Link,Category/Category&$expand=Category`;
// Category from getLinks is looking at the Category from getCategories. The data is the same.
axios.all([
axios.get(getCategories, restHeaders),
axios.get(getLinks, restHeaders)
]).then(axios.spread((cats, links) => {
let filtLinks = [];
links.data.d.results.filter((n) => {
if (n.Category) {
filtLinks.push({
"_Title": n.Title
})
}
})
let newCats = cats.data.d.results.map((m) => {
return {
"_Category": m.Category,
"_RootID": m.ID,
"_Child": {
// filter first by cats.ID, then map back to m.ID
"_Title": filtLinks,
"_Link": "test"
}
}
})
console.log(newCats)
this.setState({
cats: newCats
});
})).catch(err => {
// etc
这是filtLinks 的外观:https://i.stack.imgur.com/s8CF5.png
getCategories:https://i.stack.imgur.com/PS1Bm.png
getLinks:https://i.stack.imgur.com/DEsp2.png
getLinks 图片中的类别与我在getCategories 图片中展开的类别组相同。
【问题讨论】:
标签: javascript arrays object methods filter