js之如何刪除多層數(shù)組嵌套的最后一層中的部分數(shù)據(jù)
更新時間:2023年06月29日 10:32:39 作者:MYG_G
這篇文章主要介紹了js之如何刪除多層數(shù)組嵌套的最后一層中的部分數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
js刪除多層數(shù)組嵌套的最后一層中的部分數(shù)據(jù)
我想刪除arr中,第二個對象里面的aList中的{id:153,name: daad}的元素。
const arr = [
{
id: 1,
name: 'llaq',
aList: [
{
id: 20,
name: 'hdka',
},
{
id: 12,
name: 'loqas',
},
]
},
{
id: 2,
name: '略略略',
aList: [
{
id: 21221,
name: 'dqd',
},
{
id: 152,
name: 'daad',
},
{
id: 19522,
name: 'kka',
},
]
},
{
id: 3,
name: '哐哐哐',
aList: [
{
id: 32,
name: '32',
},
{
id: 132,
name: '32daa',
},
{
id: 1232,
name: 'da',
},
]
},
]
// id是aList中要刪除的id
const handleClose = (id: number) => {
const list = arr.map(item => {
//修改被刪除的item的數(shù)據(jù)
item.aList = item?.aList?.filter(v => v.id !== id);
return item;
})
console.log(list,'list');
};多層嵌套數(shù)組拿到每一層數(shù)據(jù),可以組成新數(shù)組,也可以把內(nèi)部數(shù)據(jù)改變
數(shù)據(jù)結構如下
data: [{
? ? ? ? ? id: 0,
? ? ? ? ? name: "1",
? ? ? ? ? children: [{
? ? ? ? ? ? ? id: 0 - 1,
? ? ? ? ? ? ? name: "0-1",
? ? ? ? ? ? ? children: [{
? ? ? ? ? ? ? ? ? id: 0 - 1 - 1,
? ? ? ? ? ? ? ? ? name: "0-1-1",
? ? ? ? ? ? ? ? ? children: [{...}]
? ? ? ? ? ? ? ? }]
? ? ? ? ? ? }]
? ? ? ? }]以此類推,數(shù)組里面還有數(shù)組,還有數(shù)組這種樣式
處理方法
tree(res) {
? ? ? for (const item of res) {
?? ?//這里可以處理很多數(shù)據(jù),比如遍歷一個數(shù)據(jù)數(shù)組匹配數(shù)據(jù)更改數(shù)據(jù)
? ? ? ? item.label = item.name;//如果label存在就是改變值,如果不存在就是往數(shù)組里面添加了一條新數(shù)據(jù)
? ? ? ? //如果item.children存在,就再調(diào)用一次函數(shù),傳數(shù)組給他,直到?jīng)]有兒子結束
? ? ? ? if (item.children) {
? ? ? ? ? this.tree(item.children);
? ? ? ? }
? ? ? }
? ? },遍歷成新數(shù)組
tree(res,list) {
? ? ? for (const item of res) {
? ? ? ? list.push(item.id)
? ? ? ? if (item.children) {
? ? ? ? ? this.tree(item.children,list);
? ? ? ? }
? ? ? }
? ? },傳數(shù)組以及需要形成的新數(shù)組,循環(huán)一次push一次,直到循環(huán)條件不成立就結束
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
JS實現(xiàn)從網(wǎng)頁頂部掉下彈出層效果的方法
這篇文章主要介紹了JS實現(xiàn)從網(wǎng)頁頂部掉下彈出層效果的方法,實例分析了javascript創(chuàng)建彈出窗口及窗口掉落與抖動效果實現(xiàn)方法,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08
使用reflect-metadata實現(xiàn)數(shù)據(jù)校驗與日志記錄
在?TypeScript?生態(tài)系統(tǒng)中,reflect-metadata?庫是一種強大的工具,它允許我們在運行時獲取更多的類型信息,下面我們來看看如何在前端項目中使用reflect-metadata以及它能實現(xiàn)的能力吧2024-12-12
使用webpack搭建pixi.js開發(fā)環(huán)境
這篇文章主要介紹了使用webpack搭建pixi.js開發(fā)環(huán)境,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02
下面給大家匯總的幾個javascript實現(xiàn)的分頁代碼,當然必須要結合后臺代碼實現(xiàn)。大家可以自行分析一下代碼,希望能夠給大家?guī)硪欢ǖ膸椭?/div> 2015-08-08最新評論

