Javascript 我如何映射和对象,它包含另一个我想映射并从中返回JSX的对象? 我的问题
我有一个mockdata对象,看起来像:Javascript 我如何映射和对象,它包含另一个我想映射并从中返回JSX的对象? 我的问题,javascript,reactjs,lodash,Javascript,Reactjs,Lodash,我有一个mockdata对象,看起来像: topicGroups: { 0: { title: "Languages", topics: { 0: { title: "Javascript", description: "Everything about Vanilla JS", latestTopic: "Diskussion] Der ideale asdf G
topicGroups: {
0: {
title: "Languages",
topics: {
0: {
title: "Javascript",
description: "Everything about Vanilla JS",
latestTopic:
"Diskussion] Der ideale asdf Gaming-PC er ideale asdf Gamin(1..."
},
1: {
title: "C#",
description: "Microsoft's go to language",
latestTopic: "Main geiles Topic alter"
}
}
},
1: {
title: "Coding Partner Search",
topics: {
0: {
title: "Suche nach Liebe",
description: "Everything about Vanilla JS",
latestTopic:
"Diskussion] Der ideale asdf Gaming-PC er ideale asdf Gamin(1..."
}
}
}
}
我希望实现以下目标:
- 映射所有主题组(以访问
字符串和标题
对象)主题
- 映射第一个映射中的
对象(因此我在组标题的范围内)主题
- 返回Jsx,其中我只使用组标题和当前主题
和title
description
主题组
之外创建另一个新对象,但是很难确定哪些主题引用了哪些主题组
我想如何使用jsx以及我想返回什么示例:
return groups.map(group =>
group.topics.map(topic => {
return (
<ForumTopicGroup title={group.title}>
<ForumTopic>{topic.title}</ForumTopic>
</ForumTopicGroup>
);
})
);
returngroups.map(组=>
group.topics.map(主题=>{
返回(
{topic.title}
);
})
);
实现这一目标的最佳和最干净的方法是什么
我之所以只使用object而不使用数组来处理数据,是因为我想处理来自firebase的数据(正如我稍后将在应用程序中使用firebase一样,如果您可以使用数组,它将像您在问题中编写的一样工作,但是由于对象没有
映射
方法,因此您可以使用它来迭代对象中的所有键值对
示例
const组={
0: {
标题:“语言”,
主题:{
0: {
标题:“Javascript”,
描述:“关于香草JS的一切”,
最新主题:
“Diskussion]Der ideale asdf Gaming PC er ideale asdf Gamin(1…”
},
1: {
标题:“C#”,
描述:“Microsoft的go to语言”,
最新主题:“主要盖尔斯主题变更”
}
}
},
1: {
标题:“编码合作伙伴搜索”,
主题:{
0: {
标题:“Suche nach Liebe”,
描述:“关于香草JS的一切”,
最新主题:
“Diskussion]Der ideale asdf Gaming PC er ideale asdf Gamin(1…”
}
}
}
};
函数App(){
返回(
{Object.entries(groups.map)([groupKey,group])=>(
{Object.entries(group.topics).map([topicKey,topic])=>{
返回(
{group.title}-{topic.title}
);
})}
))}
);
}
ReactDOM.render(,document.getElementById(“根”);
我为此编写了一个小JS函数,希望您可以使用它并将其转换为JSX
let data = {
0: {
title: "Languages",
topics: {
0: {
title: "Javascript",
description: "Everything about Vanilla JS",
latestTopic:
"Diskussion] Der ideale asdf Gaming-PC er ideale asdf Gamin(1..."
},
1: {
title: "C#",
description: "Microsoft's go to language",
latestTopic: "Main geiles Topic alter"
}
}
},
1: {
title: "Coding Partner Search",
topics: {
0: {
title: "Suche nach Liebe",
description: "Everything about Vanilla JS",
latestTopic:
"Diskussion] Der ideale asdf Gaming-PC er ideale asdf Gamin(1..."
}
}
}
};
Object.keys(data).forEach(key => {
let { title, topics } = data[key];
Object.keys(topics).forEach(key => {
console.log(`Topic title -> ${topics[key].title}`, `Group title -> ${title}`);
});
});
当你说return JSX时,你只使用组标题和当前主题,你能更具体一点你想要返回的内容吗?@LloydFrancis我很抱歉。当然,我用一个例子编辑了这篇文章。如果你有一个键为
0
,1
,…,的对象,你可能需要使用数组来代替。@Thole阅读了文章的最后一部分这篇文章是粗体的。我这样使用它是因为firebase也以这种方式获取数据。@Thole在文章中提到,这是不可能的,因为他想处理来自firebase的数据