首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >优化数组反变换

优化数组反变换
EN

Stack Overflow用户
提问于 2017-02-16 13:15:04
回答 4查看 63关注 0票数 2

我有类似如下的数据:

学生名单和他们就读的学校

代码语言:javascript
复制
[
    {
        "uid": 100,
        "name": "Adam",
        "school": {
            "id": 1,
            "name": "NYHS"
        }
    },
    {
        "uid": 101,
        "name": "Bob",
        "school": {
            "id": 2,
            "name": "PAHS"
        }
    },
    {
        "uid": 102,
        "name": "Charles",
        "school": {
            "id": 1,
            "name": "NYHS"
        }
    },
    {
        "uid": 103,
        "name": "David",
        "school": {
            "id": 3,
            "name": "MMDS"
        }
    }
]

我想把它转换成一个学校的列表,上面有参加的学生。

代码语言:javascript
复制
[
    {
        "id": 1,
        "name": "NYHS",
        "students": [
            {
                "uid": 100,
                "name": "Adam"
            },
            {
                "uid": 102,
                "name": "Charles"
            },
        ]
    },
        "id": 2,
        "name": "NYHS",
        "students": [
            {
                "uid": 101,
                "name": "Bob"
            }
        ]
    },
        "id": 3,
        "name": "MMDS",
        "students": [
            {
                "uid": 103,
                "name": "David"
            }
        ]
    },
]

我有一个它的工作版本,但它很长,而且可能没有性能。有没有更短/更快的方法呢?

不管用什么语言。

尝试使用map/reduce,我得到了独特的学校,但不确定如何将学生合并到其中。

代码语言:javascript
复制
$schools = array_reduce(
    array_map(function ($a) {
        return $a['school'];
    }, $students), 
    function ($s, $i) {
        if (count(array_filter($s, function ($j) use ($i) {
            return $j['id'] == $i['id'];
        })) == 0) {
            array_push($s, $i);
        }
        return $s;
    }, 
    array()
);
EN

Stack Overflow用户

发布于 2017-02-16 13:29:14

这里有一种方法:

代码语言:javascript
复制
function myTransform(input) {

  // Store the output of the transform as an object
  // Here I assume that the school id is unique
  var output = {};

  input.forEach((e) => {

    if (!output[e.school.id]) {

      // If the school id doesn't exist in the output then generate it, and put the school & student data into it
      output[e.school.id] = {
        id: e.school.id,
        name: e.school.name,
        students: [{
          uid: e.uid,
          name: e.name
        }]
      };
    } else {

      // If the school id exists in the output, then push the student data into it
      output[e.school.id].students.push({
        uid: e.uid,
        name: e.name
      });
    }
  });

  // Convert the output into an array
  return Object.keys(output).map((e) => output[e]);
}

我使用一个对象来存储输出,以避免使用嵌套循环(我不确定这是否是最好的方法)。最后,我将对象转换为数组。

票数 1
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42265525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档