我有类似如下的数据:
学生名单和他们就读的学校
[
    {
        "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"
        }
    }
]我想把它转换成一个学校的列表,上面有参加的学生。
[
    {
        "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,我得到了独特的学校,但不确定如何将学生合并到其中。
$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()
);发布于 2017-02-16 13:29:14
这里有一种方法:
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]);
}我使用一个对象来存储输出,以避免使用嵌套循环(我不确定这是否是最好的方法)。最后,我将对象转换为数组。
https://stackoverflow.com/questions/42265525
复制相似问题