别以为JSON.parse(JSON.stringify(data))做深拷贝无敌,对于以下这种情况,当你需要保留父级对象,即 对象存在循环引用,就会报错。

   var a = [
        {
            "id":5,
            "pid":2,
            "categoryName":"搜索行为",
        },
        {
            "id":6,
            "pid":3,
            "categoryName":"购买力",
        }
    ]
    a.map(item => {
        item.parent = item
        return item
    })
    let b = JSON.stringify(a)
    console.log(b)

 报错

 JSON.stringify方法报错:Converting circular structure to JSON

    正确的方法是:

   var a = [
        {
            "id":5,
            "pid":2,
            "categoryName":"搜索行为",
        },
        {
            "id":6,
            "pid":3,
            "categoryName":"购买力",
        }
    ]
    a.map(item => {
        item.parent = JSON.parse(JSON.stringify(item))  // 注意这里
        return item
    })
    let b = JSON.stringify(a)
    console.log(b)

  更精简的情况:

    var a = {};
    a.o = a;
    console.log(JSON.stringify(o))

  

 

相关文章:

  • 2021-10-28
  • 2022-01-13
  • 2021-05-04
  • 2021-11-06
  • 2022-12-23
  • 2021-10-14
  • 2022-12-23
  • 2021-11-01
猜你喜欢
  • 2022-12-23
  • 2021-07-09
  • 2022-12-23
  • 2021-09-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案