数组数据"/>
JavaScript处理数组数据
数据
[{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'}]}
]
循环上面数组 并把titleData中的每一项和下面这个数组中每一项进行对比,单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'}]
实现
data.forEach(item => {item.titleData.forEach(titleItem => {const match = newData.find(newItem => newItem.prop === titleItem.prop);if (match) {Object.assign(titleItem, match);}});
});
会遍历
data
数组中的每个对象,然后对每个对象的titleData
数组进行遍历。在遍历titleData
数组的过程中,会查找与newData
数组中具有相同prop
属性的对象。如果找到匹配项,则使用Object.assign
方法将匹配项的属性覆盖到titleData
数组中的相应对象上。最终,
data
数组中的titleData
数组将被更新为匹配项的属性值。
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"}
];
循环上面数组 把下面的数字和上面匹配prop,当上面数组存在下面的某一项时,将其isshow字段赋值为下面的,如果isshow为false时,将从上面数组中删除,如果不存在则追加到上面数组中
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处理数组数据
发布评论