Call the replacer *before* the object's toJSON?

怎甘沉沦 提交于 2019-12-03 03:28:44

If I understand you correct this should do the trick, I'm pretty sure this is always the object JSON.stringify is currently iterating over:

var json = JSON.stringify(obj, function(key, value) {
  if (key === "d") {
    snippet.log(getType(this[key]));
  }
  return value;
});

From MDN:

The object in which the key was found is provided as the replacer's this parameter.

So you can do this:

var obj = {
  d: new Date()
};
snippet.log(getType(obj.d));     // "[object Date]"

var json = JSON.stringify(obj, function(key, value) {
  if (key === "d") {
    snippet.log(getType(this[key]));
  }
  return value;
});

function getType(value) {
  var to = typeof value;
  if (to === "object") {
    to = Object.prototype.toString.call(value);
  }
  return to;
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!