var json = [
{
school: "學院",
title: "數學",
},
{
school: "學院",
title: "數學",
},
{
school: "學院3",
title: "數學2",
},
{
school: "學院",
title: "數學3",
},
]
//去重
var newarr = json.filter((it, index)=>{
var arrids = []
json.forEach((item,i) => {
arrids.push(item.title)
})
return arrids.indexOf(it.title) === index
})
//查找,添加
var lidev =[]
var arr = []
var cent =[]
for(var i =0;i <newarr.length;i++){
var obj = {}
cent = []
for(var j =0;j <json.length;j++){
if(newarr[i].title === json[j].title){
cent.push( json[j])
}
}
obj.zy = cent
obj.title = newarr[i].title
arr.push({obj})
}
console.log(arr)
uj5u.com熱心網友回復:
Array.forEach實作(建議):
const newArr = [], temp = {};
arr.forEach(item => {
if(!temp[item.title]) {
newArr.push({obj: {title: item.title, zy: [item]}});
temp[item.title] = {index: newArr.length - 1};
} else {
newArr[temp[item.title].index].obj.zy.push(item)
}
});
console.log(newArr);
Array.reduce實作:
const result = arr.reduce((res:, item) => {
if(!res.temp[item.title]) {
res.arr.push({obj: {title: item.title, zy: [item]}});
res.temp[item.title] = {index: res.arr.length - 1};
} else {
res.arr[temp[item.title].index].obj.zy.push(item)
};
return res;
}, {arr: [], temp: {}})
console.log(result.arr);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/224671.html
標籤:JavaScript
下一篇:vscode安裝插件提示We cannot connect to the Exiensions Marketplace at this time
