Javascript JSON数据中的部分求值

Javascript JSON数据中的部分求值,javascript,json,Javascript,Json,我的目标是准备一些JSON数据,以便传递给第三方脚本。一些JSON数据必须在本地计算—它引用本地数据或仅在本地有意义,一些只是数字或字符串数据,其他数据与函数或属性相关,这些函数或属性仅在第三方脚本运行的上下文中有意义—第三方脚本将加载其他库 简单的例子: getOptions = function () { return { num: 2 * 36e5, // evaluate now (not essential though) str: "Hello World"

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

这似乎比JSON更适合用Javascript代码来描述。您可以在闭包中封装您想要的任何属性,然后再调用它吗?如。。getColorOK hasOwnProperty看起来很有趣。问题是,我需要将所有数据发送到远程脚本。。。只是其中一些数据需要在本地进行评估,然后发送。例如,this.dataseries指的是本地存储的数据,但在目标位置需要,而其他数据只是指需要在目标位置发送以进行评估的属性或函数。然后,您应该在发送数据之前对数据进行处理。。也许不需要过滤,但那是你的决定!有太多的可能性来提供正确的答案。
var myObject = getOptions(),
    objectToSend = myObject.filter(['color', 'fn']),
    objectToUseNow = myObject.filter(['num', 'str', 'data']);