一、前言
在Vue3中,想要读取一个对象的"键---值"对(值也是一个对象),数据格式如下:
javascript
{
1:{courseName: '课程1', study: '951526', visit: '3785553'},
2:{courseName: '课程2', study: '181630', visit: '380830'},
3:{courseName: '课程3', study: '56097', visit: '37046'},
4:{courseName: '课程4', study: '8639', visit: '6843'},
5:{courseName: '课程5', study: '64882', visit: '60939'}
}
二、实现
要读取上述类型的数据,可以使用entries() 方法以及解构语法来遍历对象的"键---值"对。
1、entries(obj)方法
- 参数obj是一个对象
javascript
Object.entries(obj)
2、核心代码
javascript
// 解构赋值:读取数据
for (const [key, courseData] of Object.entries(data.value)) {
// console.log(`${courseData.courseName}`);
study.push(courseData.study);
course.push(`${courseData.courseName}`);
visit.push(`${courseData.visit}`);
}
- 代码解析:
使用entries() 方法,通过键去读取对象的每一个值;然后根据值里面的每个键再读取子对象里面对应的内容:
- 把读取到的内容分别添加到数组中,结果如下:
3、完整代码
javascript
<template>
<div></div>
</template>
<script>
import { ref } from "vue";
export default {
setup() {
const data = ref();
data.value = {
1: { courseName: "课程1", study: "951526", visit: "3785553" },
2: { courseName: "课程2", study: "181630", visit: "380830" },
3: { courseName: "课程3", study: "56097", visit: "37046" },
4: { courseName: "课程4", study: "8639", visit: "6843" },
5: { courseName: "课程5", study: "64882", visit: "60939" },
};
var course = [];
var study = [];
var visit = [];
// 解构赋值:读取数据
for (const [key, courseData] of Object.entries(data.value)) {
// console.log(`${courseData.courseName}`);
study.push(courseData.study);
course.push(`${courseData.courseName}`);
visit.push(`${courseData.visit}`);
}
console.log("course:", course);
console.log("study:", study);
console.log("visit:", visit);
},
};
</script>