[removed] Using reviver function, I seem can't get to alter all the keys, while concating the numbers

后端 未结 1 1285
隐瞒了意图╮
隐瞒了意图╮ 2020-12-22 03:23

I just want to change all the keys in batchesX. But I can\'t seem to alter all keys, because of concat. This is what I learned from post.

Please advise how I can ch

相关标签:
1条回答
  • 2020-12-22 03:46

    The return value of the reviver function only replaces values. If you need to replace keys, then use stringify and replace before the parse call, like this:

    JSON.parse(JSON.stringify({"alpha":"zulu"}).replace('"alpha":','"omega":'))
    

    Here is how to replace all numeric keys:

    function newkey()
      {
      return Number(Math.random() * 100).toPrecision(2) + RegExp.$1
      }
    
    //Stringify JSON
    var foo = JSON.stringify({"123":"ashanga", "12":"bantu"});
    
    //Replace each key with a random number without replacing the ": delimiter
    var bar = foo.replace(/\d+("?:)/g, newkey)
    
    //Parse resulting string
    var baz = JSON.parse(bar);
    

    Make sure each replaced key is unique, since duplicate keys will be removed by the parse method.

    0 讨论(0)
提交回复
热议问题