let schools=[ { id:1, zy:"qd", class:"2301" }, { id:2, zy:"qd", class:"2302" }, { id:3, zy:"java", class:"2301" }, { id:4, zy:"java", class:"2202" }, ]转化为let schools1=[ { id:1, zy:"qd", children:[ { id:11, class:"2301" }, { id:12, class:"2302" } ] }, { id:2, zy:"java", children:[ { id:21, class:"2301" }, { id:22, class:"2202" } ] } ]
时间: 2024-02-10 16:30:41 浏览: 170
class1.java
你可以使用 JavaScript 的循环和条件语句来实现将 `schools` 数组转换为 `schools1` 数组的格式。下面是一个实现示例:
```javascript
let schools = [
{
id: 1,
zy: "qd",
class: "2301"
},
{
id: 2,
zy: "qd",
class: "2302"
},
{
id: 3,
zy: "java",
class: "2301"
},
{
id: 4,
zy: "java",
class: "2202"
},
];
let schools1 = [];
let tempObj = {};
for (let i = 0; i < schools.length; i++) {
let currentSchool = schools[i];
if (!tempObj[currentSchool.zy]) {
tempObj[currentSchool.zy] = {
id: currentSchool.id,
zy: currentSchool.zy,
children: [
{
id: currentSchool.id * 10 + 1,
class: currentSchool.class
}
]
};
} else {
tempObj[currentSchool.zy].children.push({
id: currentSchool.id * 10 + tempObj[currentSchool.zy].children.length + 1,
class: currentSchool.class
});
}
}
for (let key in tempObj) {
schools1.push(tempObj[key]);
}
console.log(schools1);
```
这段代码会将 `schools` 数组转换为 `schools1` 数组的格式。它首先创建一个临时对象 `tempObj` 来存储转换后的数据。然后使用循环遍历 `schools` 数组,根据 `zy` 属性将学校分类,并将相同分类的学校放入对应的 `children` 数组中。最后,将 `tempObj` 中的值添加到 `schools1` 数组中。
运行代码后,你可以在控制台中查看转换后的 `schools1` 数组。
阅读全文