您好,我是Node.js的新手,我偶然发现了字典和数组的一个问题。我要访问的是Courseid,课程名称。
data = [
{
name: "Ole Nordmann",
pin: 1331,
Job: "Yes",
AccountNumber: 1234,
income: 50000,
loan: 1000,
Savings: 10000000,
Balance: 5500,
TransactionHistory: [
{ courseid: "CS654", coursename: "Introduction to Programming", credithours: 7.5 },
{ courseid: "CS081", coursename: "Database Management", credithours: 7.5 },
{ courseid: "CS943", coursename: "System Design", credithours: 7.5 }
]
}
答案 0 :(得分:0)
这是您的问题的解决方案。希望能帮上忙
根据您的要求,我还添加了setCourseInfo
函数以添加新课程。
const data = [
{
name: "Ole Nordmann",
pin: 1331,
Job: "Yes",
AccountNumber: 1234,
income: 50000,
loan: 1000,
Savings: 10000000,
Balance: 5500,
TransactionHistory: [
{
courseid: "CS654",
coursename: "Introduction to Programming",
credithours: 7.5,
},
{
courseid: "CS081",
coursename: "Database Management",
credithours: 7.5,
},
{ courseid: "CS943", coursename: "System Design", credithours: 7.5 },
],
},
];
const getCourseInfo = (data) => {
return data[0]["TransactionHistory"].reduce((courseInfo, course) => {
return (courseInfo += `${course.courseid} ${course.coursename}\n`);
}, ``);
};
const setCourseInfo = (newCourseData) => {
data[0]["TransactionHistory"].push(newCourseData);
}
console.log(getCourseInfo(data));
const newCourseData = {
courseid: 2323,
coursename: "This is a test ",
credithours: 32
}
setCourseInfo(newCourseData);
console.log('-----after adding new course----');
console.log(getCourseInfo(data));
答案 1 :(得分:0)
您可以通过以下方式访问课程ID和课程名称:
var courseId = data[0].TransactionHistory[0].courseid
var courseName = data[0].TransactionHistory[0].coursename
要访问阵列中的所有数据,请编写 for循环:
function a() {
var result = "";
for (var i = 0; i < data.length; i++) {
for (var j=0; j< data[i].TransactionHistory.length; j++) {
var item = data[i].TransactionHistory;
result = result + item[j].courseid + " " + item[j].coursename + "\n";
}
}
return result;
}
结果变量(由函数a返回)将具有课程ID和课程名称详细信息。
答案 2 :(得分:0)
您可以使用find
方法,其中您可以通过callback
函数进行匹配。
data = [
{
name: "Ole Nordmann",
pin: 1331,
Job: "Yes",
AccountNumber: 1234,
income: 50000,
loan: 1000,
Savings: 10000000,
Balance: 5500,
TransactionHistory: [
{ courseid: "CS654", coursename: "Introduction to Programming", credithours: 7.5 },
{ courseid: "CS081", coursename: "Database Management", credithours: 7.5 },
{ courseid: "CS943", coursename: "System Design", credithours: 7.5 }
]
}
]
const findUserByName = (name, data = []) => {
return data.find(user => user.name === name)
}
const findUserByCourseId = (courseid, data = []) => {
return data.find(user => user.TransactionHistory.some(history => history.courseid === courseid))
}
console.log(findUserByName("Ole Nordmann", data))
console.log(findUserByCourseId("CS654", data))