[英]Create array data structure from nested object of arrays in JS
[英]Create nested object array using data from two arrays
我发出两个 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 : filtLinks
getCategories: https://i.stack.imgur.com/PS1Bm.png
获取链接: https ://i.stack.imgur.com/DEsp2.png
getLinks
图片中的类别与我在getCategories
图片中展开的类别组相同。
我对它进行了很多修改,并且我能够做到。 注意 - 我更改了一些变量名称:
]).then(axios.spread((cats, links) => {
let catsData = cats.data.d.results,
linksData = links.data.d.results,
newCats = catsData.map((m) => {
let cat = m.Category,
titlesArr = [],
linksArr = [];
linksData
.filter((n) => {
if (n.Category.Category === cat) {
titlesArr.push(n.Title)
linksArr.push(n.Link)
}})
return {
"_Category": m.Category,
"_RootID": m.ID,
"_Child": {
"_Title": titlesArr,
"_Link": linksArr
}
}
})
console.log(newCats)
我不得不编辑信息,但出现在_Title
下的_Title
都属于“De...” _Category
,其他类别是相似的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.