js数组的findIndex方法用途

文章讲述了如何使用JavaScript的findIndex方法在保持数组长度不变的情况下,将dataId为自动id的对象替换为datasOld数组中不包含在原数组的其他对象。通过遍历和比较,实现了数组对象的更新。
摘要由CSDN通过智能技术生成

需求:替换datas数组中的对象:规则:保持datas长度不变,dataId不为“自动id”的值不变,dataId为“自动id”的数据为datasOld中的对象,前提该对象不包含在datas中。

定义和用法
findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。
findIndex() 方法为数组中的每个元素都调用一次函数执行:
当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。
如果没有符合条件的元素返回 -1
注意: findIndex() 对于空数组,函数是不会执行的。
注意: findIndex() 并没有改变数组的原始值。

用findIndex方法:

待处理的数据如下:

   datas=[
      {isEffective: true, dataId: "1"},
      {isEffective: true, dataId: "2",},
      {isEffective: true, dataId: "自动id"},
      {isEffective: true, dataId: "自动id",},
      {isEffective: true, dataId: "3"},
      {isEffective: true, dataId: "自动id"},
	]
	
 datasOld=[
    {isEffective: true, dataId: "1"},
    {isEffective: true, dataId: "6"},
    {isEffective: true, dataId: "7"}              
  ]

最终结果就是:

datas=[
              {isEffective: true, dataId: "1"},
              {isEffective: true, dataId: "2",},
              {isEffective: true, dataId: "6"},
              {isEffective: true, dataId: "7"},
              {isEffective: true, dataId: "3"},
              {isEffective: true, dataId: "自动id"},
            ]

处理逻辑


   datasOld.forEach(m=>{
                let index = datas.findIndex(k=>k.dataId==m.dataId);
                if (index==-1) {
                   let ind = datas.findIndex(h=>h.dataId=='自动补齐的id');
                   if (ind>-1) {
                    datas[ind] = m;
                   }
                }
            })

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值