gpt4 book ai didi

javascript - 根据与第二个属性值的匹配从 Javascript 对象检索值

转载 作者:行者123 更新时间:2023-12-02 22:45:46 24 4
gpt4 key购买 nike

如果这个问题之前已被问过很多次,我深表歉意。我彻底搜索了 Stackoverflow,但一无所获。可能是我使用了错误的搜索词或者不明白给出的解决方案如何应用于我的问题。

我有两个 Javascript 对象; 浏览量注册。两者都包含通过单独的 API 调用从学习管理系统检索的数据。这两个对象都包含一个 user_id 属性,并且每个对象中的一些记录将具有相同的 user_id 值。当 pageviews.user_idenrollments.user_id 的值匹配时,如何检索 enrollments.name 的值?

var pageviews = [{
id: 1,
page: "Home",
user_id: "100032",
},
{
id: 2,
page: "Assignment 1",
user_id: "123032",
},
{
id: 3,
page: "Discussion 2",
user_id: "147032",
},
];
var enrollments = [{
id: 1,
name: "Amy",
role: "Student",
user_id: "100032",
},
{
id: 2,
name: "Bill",
role: "Teacher",
user_id: "123032",
},
{
id: 3,
name: "Carol",
role: "Student",
user_id: "147032",
},
];

for (var id in pageviews) {
var thisUser = pageviews[id].user_id;
console.log("To match - " + thisUser);
for (var id in enrollments) {
if (enrollments[id].user_id == thisUser) {
console.log("Returned - " + enrollments[id].nane);
}
}
}

最佳答案

据我了解,您正在尝试获取与每个综合浏览 user_id 具有匹配用户 ID 的注册名称。如果这就是您想要实现的目标,那么下面的代码片段应该可以做到。祝你好运

var pageviews = [{
id: 1,
page: "Home",
user_id: "100032",
},
{
id: 2,
page: "Assignment 1",
user_id: "123032",
},
{
id: 3,
page: "Discussion 2",
user_id: "147032",
},
];
var enrollments = [{
id: 1,
name: "Amy",
role: "Student",
user_id: "100032",
},
{
id: 2,
name: "Bill",
role: "Teacher",
user_id: "123032",
},
{
id: 3,
name: "Carol",
role: "Student",
user_id: "147032",
},
];

// loop through the page views
pageviews.forEach(pageview => {

// then get the names of enrollements that matches the current pageview user_id
let enrollmentsNames = enrollments.filter(data => data.user_id === pageview.user_id).map(data => data.name);

// if the result is not empty, then log the names of enrollments that has matching user id with the current pageview user_id
if (enrollmentsNames.length) console.log(enrollmentsNames)

// if it's certain that a pageview won't have more than 1 enrollment then just go ahead and log the first element
if (enrollmentsNames.length) console.log(enrollmentsNames[0])
});

关于javascript - 根据与第二个属性值的匹配从 Javascript 对象检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58404889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com