如下的json,想根據id判斷其對應的節點下面children里面有沒有內容或有沒有children
//模擬資料1
,data1 = [{
title: '江西'
,id: 1
,children: [{
title: '南昌'
,id: 1000
,children: [{
title: '青山湖區'
,id: 10001
},{
title: '高新區'
,id: 10002
}]
},{
title: '九江'
,id: 1001
},{
title: '贛州'
,id: 1002
}]
},{
title: '廣西'
,id: 2
,children: [{
title: '南寧'
,id: 2000
},{
title: '桂林'
,id: 2001
}]
},{
title: '陜西'
,id: 3
,children: [{
title: '西安'
,id: 3000
},{
title: '延安'
,id: 3001
}]
}]
uj5u.com熱心網友回復:
/**
* 將源陣列形態進行改變,拉平層級,并以id做為單項資料的屬性名稱以便于直接查找
* @param data {any[]} 待遍歷陣列:初始時源陣列,內部查找時為對應的children節點資料
* @param json {Record<number,any>} 待回傳的新資料物件,默認值為{};它由源陣列變化而來,資料結構如下:
* @example
* {
* 1:{fid:0,id:1,title:"xx",children:[]||false},
* 1000:{fid:1,id:1000,title:"xxxx",children:[]||false}
* }
*/
function transform2Json(data: any[], json: Record<number, any> = {}) {
data.forEach(item => {
let newItem: {id: number, title: string, children?: any[]} = {
id: item.id,
title: item.title
};
item.children && (newItem.children = item.children);
json[item.id] = newItem;
item.children && transform2Json(item.children, json);
});
return json;
}
const json = transform2Json(data);
//列印
console.log(json);
//判斷id=1時是否存在children
console.log('id=1 =>',!!json[1].children);
//判斷id=10001時是否存在children
console.log('id=10001 =>',!!json[10001].children);
其中為了后續可以直接獲取children,所以children部分的資料是有冗余的。如果只是需要做個簡單判斷,不需要保留到后續使用,可將
let newItem: {id: number, title: string, children?: any[]} = {
id: item.id,
title: item.title
};
item.children && (newItem.children = item.children);
改為:
const newItem = {
id: item.id,
title: item.title,
children:!!item.children
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/269200.html
標籤:JavaScript
上一篇:爬蟲ajax抓包
下一篇:后臺登陸后一片空白不能跳轉
