JSON数据中的部分评估

时间:2014-10-12 18:22:10

标签: javascript json

我的目标是准备一些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;
           }
        }
   };

}

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

谢谢!

1 个答案:

答案 0 :(得分:0)

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

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']);
相关问题