JavaScript处理数组数据

编程入门 行业动态 更新时间:2024-10-24 22:24:01

JavaScript处理<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组数据"/>

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处理数组数据

本文发布于:2023-12-04 01:07:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1659310.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   数据   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!