吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1604|回复: 2
收起左侧

[其他转载] 分享一个JS递归遍历数组和对象,并替换指定字符的函数

[复制链接]
cqwcns 发表于 2021-9-12 21:48
工作需要,有一个JS对象中可能包含一个或多个字符串'dbServerDate',而且位置不定,我需要将它替换为另一个符号,例如db.serverDate()(微信小程序云函数的服务器时间)。
可见db.serverDate()的个值使用JSON.parse+JSON.stringify是对报错的,所以自己写了一个递归来实现替换,分享一下代码。也欢迎各位指教。


[Asm] 纯文本查看 复制代码
   // 递归遍历并替换指定值
  funForIn(data) {
    for (let i in data) {
      if (Object.prototype.toString.call(data[i]) === '[object Array]' || Object.prototype.toString.call(data[i]) === '[object Object]') {
        that.funForIn(data[i])
      } else {
        if (data[i] == 'dbServerDate') {
          data[i] = db.serverDate()
        }
      }
    }
  },

// 调用

   const data = {
      name: 'playCloud',
      data: {
        doWhat: 'add',
        collection: 'staff',
        data: {
          field1: 'field1val',
          field2: 123,
          field3: {
            test3: 'test33',
            test333: 666666666,
            time: 'dbServerDate'
          },
          field4: ['aa', 321, 'bb', 'dbServerDate'],
          field5: true,
          field6: {
            "type": "Point",
            "coordinates": [113, 23]
          },
          field7: 'dbServerDate'
        }
      }
    }

    that.funForIn(data)

    console.log(data)

免费评分

参与人数 1吾爱币 +3 热心值 +1 收起 理由
苏紫方璇 + 3 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

头像被屏蔽
麦子1995 发表于 2021-9-13 09:04
提示: 作者被禁止或删除 内容自动屏蔽
chenjunuyue520 发表于 2021-9-22 10:24
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-6-16 15:57

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表