如何访问主题数组内部的 name 属性?
数据库是mongodb。 无法更改类(class)模型。
类(class)模式:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SubjectSchema = new Schema({
name : {
type : String
},
description : {
type : String
},
amount : {
type : Number
},
});
//course schema
const CourseSchema = new Schema({
name: {
type : String
},
code : {
type: String
},
passMark : {
type : Number
},
lectureInCharge : {
type : String
},
subjects : {
type : [SubjectSchema]
}
});
//creating model
const Course = mongoose.model('course', CourseSchema);
module.exports = Course;
我想要访问类(class)主题详细信息的代码? 我想显示类(class)详细信息以及其中的主题详细信息 类(class)详情。但主题位于一个数组内,该数组被分配给类(class)对象的主题属性。
这是一个 react 接口(interface)。
const courses = this.state.courses;
const updatedCourse = courses.map(function (data, index) {
return (
<div key={index}>
<p> Name : {data.name}</p>
<p> Code : {data.code}</p>
<p> Pass Mark : {data.passMark}</p>
<p> lecture in charge : {data.lectureInCharge}</p>
<p> Subjects : </p>
//Here i want aceess the ame property of the inside the
subjects array?
<p> Subject name : {data.subjects.name}</p>
</div>
)
});
从数据库检索的 json 如下所示。 包括在内以了解数据库的外观。
[
{
"_id": "5cf348111b0ffd3bc02304b8",
"name": "Software Engineering",
"code": "SE2019",
"passMark": 75,
"lectureInCharge": "Jhon Smith",
"subjects": [
{
"_id": "5cf348111b0ffd3bc02304b9",
"name": "Computer Architecture",
"description": "PC Architecture x86 and x64",
"amount": 2500
}
],
"__v": 0
},
{
"_id": "5cf358991b0ffd3bc02304ba",
"name": "Computer Networking",
"code": "CN2019",
"passMark": 75,
"lectureInCharge": "Jimmy Perera",
"subjects": [
{
"_id": "5cf358991b0ffd3bc02304bc",
"name": "Wireless Communications",
"description": "Introduction to Wireless Communications",
"amount": 5000
},
{
"_id": "5cf358991b0ffd3bc02304bb",
"name": "Network Technology Project",
"description": "Introduction to Network Technology Project",
"amount": 7000
}
],
"__v": 0
},
{
"_id": "5cf3593d1b0ffd3bc02304c0",
"name": "IM",
"code": "IM2019",
"passMark": 75,
"lectureInCharge": "IMIM Jimmy Perera",
"subjects": [
{
"_id": "5cf3593d1b0ffd3bc02304c2",
"name": "IM Wireless Communications",
"description": " IM Introduction to Wireless Communications",
"amount": 3000
},
{
"_id": "5cf3593d1b0ffd3bc02304c1",
"name": "IM Network Technology Project",
"description": "IM Introduction to Network Technology Project",
"amount": 7700
}
],
"__v": 0
}
]
最佳答案
由于它是一个数组,因此您需要一个内部循环(可能是另一个map
):
const courses = this.state.courses;
const updatedCourse = courses.map(function (data, index) {
return (
<div key={index}>
<p> Name : {data.name}</p>
<p> Code : {data.code}</p>
<p> Pass Mark : {data.passMark}</p>
<p> lecture in charge : {data.lectureInCharge}</p>
<p> Subjects : </p>
{data.subjects.map(({name}, i) => ( // <===
<p key={i}> Subject name : {name}</p> // <===
)}
</div>
);
});
关于javascript - 如何访问分配给另一个对象的属性的数组内的对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56413210/