JavaScript處理數(shù)組數(shù)據的示例詳解
數(shù)據
[ { title: '市值', prop: 'sz', titleData: [ { title: '市值', label: '市值', prop: 'sz', isShow: false, fixed: false, width: 100, align: 'left' }, { title: '持倉/市值', label: '持倉/市值', prop: 'ccsz', isShow: false, fixed: false, width: 120, align: 'left' } ] }, { title: '持倉', prop: 'cc', titleData: [ { title: '資金費率', label: '資金費率', prop: 'avgFundingRateByOi', isShow: false, fixed: false, width: 100, align: 'left' }, { title: '持倉', label: '持倉', prop: 'openInterest', isShow: false, fixed: false, width: 100, align: 'left' } ] } ]
循環(huán)上面數(shù)組 并把titleData中的每一項和下面這個數(shù)組中每一項進行對比,單prop相等時,將下面的匹配項覆蓋到上面對應的位置
[{ title: '持倉', label: '持倉', prop: 'openInterest', fixed: false, width: 100, isShow: true, align: 'left' }, { title: '持倉變化(24h)', label: '持倉(24h%)', prop: 'h24OiChangePercent', fixed: false, width: 100, isShow: true, align: 'left' }, { title: '多(4小時)', label: '多(4h)', prop: 'h4LongVolUsd', fixed: false, width: 100, isShow: true, align: 'left' }]
實現(xiàn)
data.forEach(item => { item.titleData.forEach(titleItem => { const match = newData.find(newItem => newItem.prop === titleItem.prop); if (match) { Object.assign(titleItem, match); } }); });
會遍歷data數(shù)組中的每個對象,然后對每個對象的titleData數(shù)組進行遍歷。在遍歷titleData數(shù)組的過程中,會查找與newData數(shù)組中具有相同prop屬性的對象。如果找到匹配項,則使用Object.assign方法將匹配項的屬性覆蓋到titleData數(shù)組中的相應對象上。
最終,data數(shù)組中的titleData數(shù)組將被更新為匹配項的屬性值。
const data = [ { label: "收藏", prop: "sc", fixed: true, width: 60, isShow: true, align: "center" }, { label: "排名", prop: "pm", fixed: true, width: 60, isShow: true, align: "center" }, { label: "幣種", prop: "symbol", fixed: true, width: 90, isShow: true, align: "left" }, { label: "價格", prop: "price", fixed: false, width: 100, isShow: true, align: "left" }, { title: "價格變化(24h)", label: "價格(24h%)", prop: "h24PriceChangePercent", fixed: false, width: 100, isShow: true, align: "left" } ];
循環(huán)上面數(shù)組 把下面的數(shù)字和上面匹配prop,當上面數(shù)組存在下面的某一項時,將其isshow字段賦值為下面的,如果isshow為false時,將從上面數(shù)組中刪除,如果不存在則追加到上面數(shù)組中
const newData = [ { title: '持倉', label: '持倉', prop: 'openInterest', fixed: false, width: 100, isShow: true, align: 'left' }, { title: '持倉變化(24h)', label: '持倉(24h%)', prop: 'h24OiChangePercent', fixed: false, width: 100, isShow: false, align: 'left' }, { title: '多(4小時)', label: '多(4h)', prop: 'h4LongVolUsd', fixed: false, width: 100, isShow: true, align: 'left' } ];
使用
newData.forEach(newItem => { const matchIndex = data.findIndex(item => item.prop === newItem.prop); if (matchIndex !== -1) { if (newItem.isShow) { data[matchIndex].isShow = true; } else { data.splice(matchIndex, 1); } } else { data.push(newItem); } }); console.log(data);
到此這篇關于JavaScript處理數(shù)組數(shù)據的示例詳解的文章就介紹到這了,更多相關JavaScript處理數(shù)組數(shù)據內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JS如何實現(xiàn)form表單登錄驗證并使用MD5加密詳解
表單驗證為終端用戶檢測無效的數(shù)據并標記這些錯誤,是一種用戶體驗的優(yōu)化,下面這篇文章主要給大家介紹了關于JS如何實現(xiàn)form表單登錄驗證并使用MD5加密的相關資料,需要的朋友可以參考下2023-06-06