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

Asked

Viewed 193 times

1

I need to create a function that works over all parameters of a JSON object to search for 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 with only 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 the level of it. 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 you happen to change anything in my backend scope, I’ll have to go back and implement that too, which is unnecessary with a recursive function.

Any suggestions?

  • 2

    Not knowing which format versions you will receive is difficult to predict. Doubts: - why not use the parameter -xxxx of that date? - do you know if at least this webservice will always send timestamps? in that case you could use only .match(/\d{13}/) and serves for all cases where there is a timestamp if the dates are modern.

  • Yes, the webservice I know will send this format of data timestamps but in different fields.. instead of me doing a field-by-field treatment, I would prefer that where he hit a param.indexOf('Date(') it run the function in that parameter, updating the same.

  • in addition, the function corrigeData() above already makes the replacement I want, just need to know how to run it in all parameters independent of the level within the JSON

  • Use the 13 digits that are timestamp giving a new date on it you already know has the date. And try to map the formats, and invalidate if something very unusual comes along. Webservice should support the dates concisely.

  • Leandro, is it something like that? -> https://jsfiddle.net/j3Lquh7j/

2 answers

1

To check the fields inside an unknown depth object you have to 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: https://jsfiddle.net/j3Lquh7j/

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 fields /Date(, no matter what level of nesting they are at. However note that your corrigeData has some problem in processing already it returns "Invalid date" always, as this was not your question I did not debug to see the error.

  • yes I saw here that you are with a mistake, it is because of the type of Timezone... but I have found how to solve, thanks partner!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.