【问题标题】:Looping through multiple collection of arrays循环遍历多个数组集合
【发布时间】:2022-01-27 10:46:16
【问题描述】:

我有很多未解析的响应数据,因此您可以查看响应中的内容。但我想要表格结果中的所有分数,actorId 上的 quary 拟合器,categoryId,从该特定actorId 获取所有主题的所有数据。

如何显示按actorid和categoryid过滤的所有分数,我可以看到分数列在结果数组中。

来自我的本地主机的解析数据响应:

[
{
"id": 1,
"name": "Word",
"tests": [
{
"id": 1,
"title": "Test  1",
"name": "Test 1",
"description": "This is the description of the first Test",
"totalPoints": 2,
"duration": 30,
"level": 1,
"subjectId": 1,
"questions": [ ],
"paragraphs": [ ],
"results": [
{
"id": 22,
"score": 100.0,
"timeElapsed": 5,
"actorId": 13,
"actor": null,
"testId": 1,
"resultQuestions": [ ],
"resultSliders": [ ]
}
],
"sliders": [ ],
"pausedTests": [ ]
},
{
"id": 5,
"title": "new test",
"name": "new test",
"description": "asdf",
"totalPoints": 0,
"duration": 9,
"level": 3,
"subjectId": 1,
"questions": [ ],
"paragraphs": [ ],
"results": [
{
"id": 19,
"score": 0.0,
"timeElapsed": 4,
"actorId": 13,
"actor": null,
"testId": 5,
"resultQuestions": [ ],
"resultSliders": [ ]
}
],
"sliders": [ ],
"pausedTests": [ ]
},
{
"id": 8,
"title": "test",
"name": "test-1",
"description": "Dit is een test",
"totalPoints": 2,
"duration": 1,
"level": 1,
"subjectId": 1,
"questions": [ ],
"paragraphs": [ ],
"results": [ ],
"sliders": [ ],
"pausedTests": [ ]
}
],
"schools": [ ],
"categoryId": 1,
"category": null
},

如果您从 console.log(response) 控制台记录 API 的响应,则返回的数据:

The function is called [{"id":1,"name":"Word","tests":[{"id":1,"title":"Test  1","name":"Test 1","description":"This is the description of the first Test","totalPoints":2,"duration":30,"level":1,"subjectId":1,"questions":[],"paragraphs":[],"results":[{"id":22,"score":100.0,"timeElapsed":5,"actorId":13,"actor":null,"testId":1,"resultQuestions":[],"resultSliders":[]}],"sliders":[],"pausedTests":[]},{"id":5,"title":"new test","name":"new test","description":"asdf","totalPoints":0,"duration":9,"level":3,"subjectId":1,"questions":[],"paragraphs":[],"results":[{"id":19,"score":0.0,"timeElapsed":4,"actorId":13,"actor":null,"testId":5,"resultQuestions":[],"resultSliders":[]}],"sliders":[],"pausedTests":[]},{"id":8,"title":"test","name":"test-1","description":"Dit is een test","totalPoints":2,"duration":1,"level":1,"subjectId":1,"questions":[],"paragraphs":[],"results":[],"sliders":[],"pausedTests":[]}],"schools":[],"categoryId":1,"category":null},{"id":2,"name":"PowerPoint","tests":[{"id":2,"title":"Test  2","name":"Test 1","description":"This is the description of the first Test","totalPoints":2,"duration":30,"level":2,"subjectId":2,"questions":[],"paragraphs":[],"results":[],"sliders":[],"pausedTests":[]},{"id":3,"title":"De titel der titelen","name":"Deze test heet programmeren voor gevorderden","description":"Deze test gaat over hoe leraren ict moet leren begrijpen.","totalPoints":25,"duration":30,"level":3,"subjectId":2,"questions":[],"paragraphs":[],"results":[{"id":20,"score":44.0,"timeElapsed":50,"actorId":13,"actor":null,"testId":3,"resultQuestions":[],"resultSliders":[]}],"sliders":[],"pausedTests":[]}],"schools":[],"categoryId":1,"category":null},{"id":3,"name":"Excel","tests":[],"schools":[],"categoryId":1,"category":null},{"id":7,"name":"Test","tests":[],"schools":[],"categoryId":1,"category":null}]

如果我能从结果数组表中取回分数,我自己试了一下。

function showAllSubjectsScores(response) {
    var parsedData = JSON.parse(response);

console.log('The function is called', parsedData[results][0].score)
    
}

这是对所有数据的响应进行 APi 调用的方式:

// Global var's
var categoryId = 1;
var actorId = 13; // This is my actorId
var websiteUrl = localStorage.getItem('url');

function getSubjectsByActorid() {
    var xHttp = new XMLHttpRequest();
    xHttp.onreadystatechange = function () {
        if (xHttp.readyState == XMLHttpRequest.DONE) {

            var response = xHttp.response;
            if (xHttp.status == 200) {
                console.log('ANTWOORD IS TERUG VAN DE SERVER')

                showAllSubjectsScores(response);

            } else {
                console.log(response);
                console.log(xHttp.status);

            }
        }
    };

    xHttp.onerror = function () {
        console.log(xHttp.statusText);
    };

    xHttp.open("GET", websiteUrl + "/api/Subjects/" + categoryId + "/" + actorId, true);

    xHttp.send();
    console.log('AANVRAAG IS VERZONDEN')
}
function showAllSubjectsScores(response) {
    var parsedData = JSON.parse(response);

    console.log('The function is called', response)
    
}
getSubjectsByActorid();


This is how the api quarry is build:

// GET: api/Subjects
        [HttpGet("/api/Subjects/{categoryId}/{actorId}")]
        public async Task<ActionResult<List<Subject>>> GetSubjectResults(int categoryId, int actorId)
        {
        var subjectResults = _context.Subjects
       .Where(i => i.CategoryId == categoryId)
       .Include(t => t.Tests)
       .ThenInclude(r => r.Results.Where(a => a.ActorId == actorId))
        .AsNoTracking().ToListAsync();

            if (subjectResults == null)
            {
                return StatusCode(204);
            }

            return await subjectResults;
        }

【问题讨论】:

  • 那么...你有什么问题?
  • 正如我所说的,我有很多数据,从响应中我想返回所有分数,这是按 actorid 和 categoryid 排序的,问题是我如何显示每个 actorid 的所有分数过滤 categorieid,我试过的东西不起作用
  • 看起来你访问你的对象错误。parsedData[results][0].score --> parsedData[0].tests[0].results[0].score
  • 我认为对象/地图/数组设计对于一个应用程序以及您如何在瞬间访问相关信息至关重要。总体而言,没有对问题发表评论似乎上面的评论解决了它。我建议不要担心多个字典可以更快地引用!
  • @kemicofaghost 它工作得很好,但我怎样才能循环通过 a.l 响应的分数

标签: javascript arrays api linq


【解决方案1】:

使用 Newtonsoft 库解析 JSON 和一些类型化的类以将 JSON 转换为可行的东西,您可以执行以下操作。

SelectMany 运算符将列表展开为父列表中的项。由于 JSON 有许多内部列表,因此这是一种将其汇总的方法。

请注意,我从您的示例中删除了所有与您的问题无关的无关 JSON 属性,以保持答案简短明了,但您可以将它们添加到您的最终实现中。

结果如下:

CategoryId: 1, ActorId: 13, Score: 100.0
CategoryId: 1, ActorId: 13, Score: 0.0

这是工作代码示例:

void Main()
{
    var data = JsonConvert.DeserializeObject<IEnumerable<Category>>(GetData());

    var result = data
        .GroupBy(x => x.CategoryId)
        .SelectMany(grp => grp.Select(
            g => g.Tests.SelectMany(
                t => t.Results).Select(
                    t => new {CategoryId = grp.Key, t.ActorId, t.Score})))
        .SelectMany(grp => grp);
    
    foreach (var x in result)
    {
        Console.WriteLine($"CategoryId: {x.CategoryId}, ActorId: {x.ActorId}, Score: {x.Score}");
    }
}

public static string GetData()
{
    return @"
        [
            {
                ""tests"":
                [
                    {
                        ""results"":
                        [
                            {
                                ""score"": 100.0,
                                ""actorId"": 13
                            }
                        ]
                    },
                    {
                        ""results"":
                        [
                            {
                                ""score"": 0.0,
                                ""actorId"": 13
                            }
                        ]
                    }
                ],
                ""categoryId"": 1
            }
        ]"; 
}

public class Category
{
    public int CategoryId { get; set; }
    public IEnumerable<Test> Tests { get; set; }
}

public class Test
{
    public IEnumerable<Result> Results  { get; set; }
}

public class Result
{
    public int ActorId { get; set; }
    public decimal Score { get; set; }
}

【讨论】:

    猜你喜欢
    • 2021-09-12
    • 2011-08-28
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2016-07-16
    相关资源
    最近更新 更多