导航栏: 首页 评论列表

深度遍历,替换掉value中的'123'

默认分类 2023/07/06 20:29

深度遍历,将所有value中的'123'去掉,key中的'123'不用管:

const walk = (obj) => {
  const type = (kk) => Object.prototype.toString.call(kk).replace(/(\[object |])/g, '');
  const fmt = (val) => {
    if (['Object', 'Array'].includes(type(val))) {
      walk(val);
      return val;
    }
    if (type(val) !== 'String') return val;
    return val.replace(/123/g, '')
  };

  if (type(obj) === 'Object') {
    for (let i in obj) {
      if (!obj.hasOwnProperty(i)) continue;
      obj[i] = fmt(obj[i]);
    }
  } else if (type(obj) === 'Array') {
    for (let i = obj.length - 1; i > -1; i--) {
      obj[i] = fmt(obj[i]);
    }
  }
};
let aa = {a:'aa123bb', aa123bb: '456'}
walk(aa)
console.log(aa)
// {a:'aabb', aa123bb: '456'}


>> 留言评论