使用Javascript:齐磊使用功能,我似乎无法得到改变所有的按键,而concating号码([r

2019-09-02 05:12发布

我只是想改变batchesX所有的按键。 但我似乎无法改变所有的按键,因为CONCAT的。 这是我从教训后 。

请告知我如何可以改变所有的数字键。

var batchesX = '[{"batch":"0010002033"},{"batch":"0010001917"},{"batch":"0000020026"},{"batch":"0000017734"},'+
                    '{"batch":"0000015376"},{"batch":"0000014442"},{"batch":"0000014434"},{"batch":"0000014426"},'+
                    '{"batch":"0000013280"},{"batch":"0000012078"},{"batch":"0000012075"},{"batch":"0000012072"},'+
                    '{"batch":"0000011530"},{"batch":"0000011527"},{"batch":"0000011342"},{"batch":"0000010989"},'+
                    '{"batch":"0000010477"},{"batch":"0000008097"},{"batch":"0000007474"},{"batch":"0000006989"},'+
                    '{"batch":"0000004801"},{"batch":"0000003566"},{"batch":"0000003565"},{"batch":"0000001392"},'+
                    '{"batch":"0000001391"},{"batch":"0000000356"},{"batch":"0000"},{"batch":"000"},{"batch":""},'+
                    '{"batch":null}]'; // 30 elements
                    //in JSON text

    var batchi = "batch";

    var obj_batchesY = JSON.parse(batchesX);
    console.debug(obj_batchesY);

    var obj_batchesYlength = obj_batchesY.length;
    console.debug(obj_batchesYlength);

    var obj_batchesX = JSON.parse(batchesX, 
        function(k,v)
        {
            for(var i=1; i <= obj_batchesYlength; i++ )
            {

                if(k=="batch")
                {
                    this.batchi.concat(string(i)) = v;
                }
                else
                    return v;
            }
        }

    );
    console.debug(obj_batchesX);

是代码太长了嗦?

提前谢谢了。 克莱门特

Answer 1:

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.



文章来源: Javascript: Using reviver function, I seem can't get to alter all the keys, while concating the numbers