JSON数据中的部分求值

Partial evaluation in JSON data

本文关键字:数据 JSON      更新时间:2023-09-26

我的目标是准备一些JSON数据,以便传递给第三方脚本。一些JSON数据必须在本地进行评估(它指的是本地数据或仅在本地具有意义),一些只是数字或字符串数据,而其他数据与函数或属性有关,这些函数或属性仅在第三方脚本运行的上下文中具有意义(第三方剧本将加载其他库)。

简单示例:

getOptions = function () {
  return {
    num: 2 * 36e5,   // evaluate now (not essential though)
    str: "Hello World",  // just a string
    data: this.dataseries,   // evaluate now (load local data for use at destination)
    color: RemoteObj.getOptions().colors[2],   // only has meaning at destination... don't try to evaluate now
    fn: function () {                          // for use only at destination
           if (this.y > 0) {
              return this.y;
           }
        }
   };
}

实现这一点最简单的方法是什么?

谢谢!

您可以过滤您需要的属性并忽略其他属性,然后将正确的对象发送到其目的地,如下所示:

Object.defineProperty(Object.prototype, 'filter', {
    value: function(keys) {
        var res = {};
        for (i=0; i < keys.length; i++) {
            if (this.hasOwnProperty(keys[i])) res[keys[i]] = this[keys[i]];
        }
        return res;
    }
});
var myObject = {
    key1: 1, // use now
    key2: 2, // use now
    key3: "some string", // use at destination
    key4: function(a) { // use now
        return a+1
    },
    key5: [1,2,3] // use at destination
}
var objectToSend = myObject.filter(['key3', 'key5']);
// now objectToSend contains only key3 and key5
console.log(objectToSend);
> Object {key3: "some string", key5: [1, 2, 3]}

因此,在您的情况下,您将执行:

var myObject = getOptions(),
    objectToSend = myObject.filter(['color', 'fn']),
    objectToUseNow = myObject.filter(['num', 'str', 'data']);