当我们从后端服务器获取数据想渲染到页面中时,当请求到的是这样数据
{id: 1, title: '文章1', categoryId: 1},
{id: 2, title: '文章2', categoryId: 2},
{id: 3, title: '文章3', categoryId: 3},
{id: 4, title: '文章4', categoryId: 1},
其中在数据库中categoryId作为外键与分类表中的id关联
我们把categoryId直接渲染到页面中是不合适的,应该渲染的是其对应的分类名称
<script>
let articalList = [] // 文章列表
const categoryList = [
{id: 1, name: '历史'},
{id: 2, name: '科技'},
{id: 3, name: '体育'}
] // 获取的分类列表
function getArticalList() {
// 模拟获取文章列表
articalList = [
{id: 1, title: '文章1', categoryId: 1},
{id: 2, title: '文章2', categoryId: 2},
{id: 3, title: '文章3', categoryId: 3},
{id: 4, title: '文章4', categoryId: 1},
] // 当作是从服务器获取的文章列表
// 为文章列表每一项动态添加 categoryName 属性,值为对应分类名称 => item.categoryName = ...
articalList.forEach(item => {
item.categoryName = categoryList.find(category => category.id === item.categoryId).name
})
/*
1.forEach() 方法对数组的每个元素执行一次给定的函数。=> 对文章列表每一个{id: , title: , categoryId: }进行操作
2.find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
=> 遍历分类列表,从分类列表中找到 id 与文章列表当前项的 categoryId 相同的分类,并返回该分类
3.最后,将找到的分类的 name 属性赋值给文章列表当前项的 categoryName 属性
*/
}
getArticalList()
console.log(articalList)
</script>
这样就可以将articalList 渲染到页面中了