问答

js根据规则替换json中所有key值

作者:admin 2021-05-06 我要评论

自己写了半天还是无法实现,最多只能替换一层的key,多层太难了 let result = {};Object.keys(property).forEach(key = { let value = property[key]; if ({}.to...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

自己写了半天还是无法实现,最多只能替换一层的key,多层太难了

let result = {};
Object.keys(property).forEach(key => {
       let value = property[key];

       if ({}.toString.call(value) === '[object Object]') {
         value = Object.keys(property[key])[0];
       }

       if (data.hasOwnProperty(value)) {
         result[key] = data[value];
       }
     })

需要替换的规则

const property = {
            userId: 'user_id',
            userName: 'user_name',
            product: {
                'order_attrs': {
                    attrId: 'id',
                    attrName: 'attr_name',
                    attrValue: 'attr_value'
                }
            },
            userAddress: {
                'address': {
                    region: 'region',
                    avatar: 'image_url',
                    phoneNumber: {
                        'phone': {
                            one: 'a',
                            two: 'b'
                        }
                    }
                }
            }
        }

需要替换的数据

const data = {
            user_id: '652',
            user_name: '思否',
            order_attrs: [{
                id: 345,
                attr_name: '型号',
                attr_value: 'iphone'
            },
            {
                id: 1897,
                attr_name: '容量',
                attr_value: '256G'
            }
            ],
            address: {
                region: '北京市',
                image_url: '/xxx/aaa.jpg',
                phone: {
                    a: 'eeee',
                    b: 'ccc'
                }
            }
        }

替换的结果

const result = {
            userId: '652',
            userName: '思否',
            product: [{
                attrId: 345,
                attrName: '型号',
                attrValue: 'iphone'
            },
            {
                attrId: 1897,
                attrName: '容量',
                attrValue: '256G'
            }
            ],
            userAddress: {
                region: '北京市',
                imageUrl: '/xxx/aaa.jpg',
                phoneNumber: {
                    one: 'eeee',
                    two: 'ccc'
                }
            }
        }
###

规则有点复杂 最好是优化设计。

###

如果无法重新设计,可以尝试广度优先遍历,一层层替换

###
function replaceObj(sourceObj, rule) {
  function getEntries(obj) {
    return Object.entries(obj).map(item => {
      const isObj = Object.prototype.toString.call(item[1]) === '[object Object]'
      const obj = {}
      obj[item[0]] = isObj ? Object.keys(item[1])[0] : item[1]
      return isObj ? [obj, getEntries(item[1])] : obj
    }).flat(Infinity)
  }

  let result = JSON.stringify(sourceObj)
  getEntries(rule).forEach(item => {
    const reg = new RegExp(`"${Object.values(item)[0]}"`, 'g')
    result = result.replace(reg, `"${Object.keys(item)[0]}"`)
  })
  return JSON.parse(result)
}

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • js根据规则替换json中所有key值

    js根据规则替换json中所有key值

  • React.memo为什么不是默认行为?

    React.memo为什么不是默认行为?

  • 如何定义纯数字的字符串类型在TypeScri

    如何定义纯数字的字符串类型在TypeScri

  • vue后端获取json正确,console出来的数

    vue后端获取json正确,console出来的数

腾讯云代理商
海外云服务器