Function for handling all date type parameters in a multilevel object with Javascript

1

I need to create a function that works on all the parameters of a JSON object to look up data fields and manipulate them. Basically the object I can receive is something like:

{
  idPedido:1,
  dataCriado: "/Date(1454637600000-0200)/",
  cliente: "Nome do Cliente",
  pagamento:[
    {
      idPgto:1,
      valor: 100.00,
      tipoPgto:"dinheiro",
      dataVenc:"/Date(1454637600000-0200)/"
    },
    {
      idPgto:2,
      valor: 100.00,
      tipoPgto:"cartão",
      dataVenc:"/Date(1454657600000-0200)/"
    }
  ],
  produtos:[
    {
      idProduto:1,
      descricao:"bola",
      valor:200.00
    }
  ]
}

My problem is that there may be numerous variants that contain this date format (unfortunately the webservice I'm being forced to work on just sends me this way ...)

I need to know how I can do a function that I can apply to all parameters that exist within JSON, regardless of its level. today the function I'm using is this:

function corrigeData(d) {
  if(d.indexOf('Date('){
    d = d.replace(/\/Date\(/g, '').replace(/\)\//g, '');
    d = new Date(d);
  };
  return d;
}

The problem is that I have to pick up and know where I'll probably find the date field. But if by chance you change something in my backend scope, I'll have to go back and implement that as well, which is unnecessary with a recursive function.

Any suggestions?

    
asked by anonymous 10.02.2016 / 18:12

2 answers

1

A recursive function:

var jsonObj = {
  idPedido:1,
  dataCriado: "/Date(1454637600000-0200)/",
  cliente: "Nome do Cliente",
  pagamento:[
    {
      idPgto:1,
      valor: 100.00,
      tipoPgto:"dinheiro",
      dataVenc:"/Date(1454637600000-0200)/"
    },
    {
      idPgto:2,
      valor: 100.00,
      tipoPgto:"cartão",
      dataVenc:"/Date(1454657600000-0200)/"
    }
  ],
  produtos:[
    {
      idProduto:1,
      descricao:"bola",
      valor:200.00
    }
  ]
};

function corrigeData(d) {
	d = d.replace(/\/Date\(/g, '').replace(/\)\//g, '');
	d = new Date(d);
	return d;
};

function applyToDateFields(object, fn) {
	for (var i in object) {
		var item = object[i];
		var type = typeof item;
		
		if (type === 'string' && item.indexOf('/Date(') !== -1) {
			object[i] = fn(object[i]);
		}
		else if (type === 'object') {
			applyToDateFields(item, fn);
		}
	}
};

applyToDateFields(jsonObj, corrigeData);

console.log(jsonObj);
document.write(JSON.stringify(jsonObj));

corrigeData will be applied to all /Date( fields, no matter what nesting level they are. However, note that your corrigeData has some processing problem, it already returns "Invalid date" always, since that was not your question I did not debug to see the error.

    
10.02.2016 / 19:19
1

To check the fields within an object of unknown depth you must use a recursive function. Something like this:

var regex = /Date\(([^\)]+)\)/;
var timestamp = /(\d{12,13})/

function converterData(obj, regex) {
    Object.keys(obj).forEach(function(key) {
        if (obj[key] instanceof Object) converterData(obj[key], regex);
        else if (typeof obj[key] == 'string' && obj[key].match(regex)) {
            var ts = parseInt(obj[key].match(timestamp)[0], 10);
            obj[key] = new Date(ts);
        }
    });
    return obj;
}
var saida = converterData(entrada, regex);

Example: link

    
10.02.2016 / 19:18