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

790 views Asked by At

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 change all keys with numbers.

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);

Is the code too long winded?

Many thanks in advance. Clement

1

There are 1 answers

0
Paul Sweatte On

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.