我的模拟数据对象看起来像这样:
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..."
}
}
}
}
我想实现以下目标:
title
字符串和topics
对象。topics
对象上进行地图映射(所以我在组标题范围内)title
和description
我尝试了几个lodash函数,但是无法正常工作。我得到的最接近的结果是创建除topicGroups
之外的另一个新对象,但是然后很难弄清楚哪个主题引用了哪个topicGroups。
示例如何使用jsx以及返回的内容:
return groups.map(group =>
group.topics.map(topic => {
return (
<ForumTopicGroup title={group.title}>
<ForumTopic>{topic.title}</ForumTopic>
</ForumTopicGroup>
);
})
);
实现此目标的最好,最干净的方法是什么?
之所以让我的数据只像对象一样,而不是使用数组,是因为我想像使用Firebase一样处理这些数据(因为我稍后将在应用程序中使用Firebase >
答案 0 :(得分:1)
如果可以使用数组,它将像您在问题中所写的那样工作,但是由于对象没有map
方法,因此可以使用Object.entries
来遍历所有键对象中的“-值”对。
示例
const groups = {
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..."
}
}
}
};
function App() {
return (
<div>
{Object.entries(groups).map(([groupKey, group]) => (
<div key={groupKey}>
{Object.entries(group.topics).map(([topicKey, topic]) => {
return (
<div key={topicKey}>
{group.title} - {topic.title}
</div>
);
})}
</div>
))}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
答案 1 :(得分:0)
我为此编写了一个小型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}`);
});
});