使用JSON中的方法创建JS对象 [英] Creating JS Object with methods from JSON

查看:67
本文介绍了使用JSON中的方法创建JS对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以下物品:

var myObj={
    "rules": {
        "email": {
            "required": true,
            "email": true,
            "remote": {
                "url": "check-email.php",
                "type": "post",
                "data": {
                    "someName1": function() {
                        return $( '#someID1' ).val();
                    },             
                    "someName2": function() {
                        return $( '#someID2' ).val();
                    },             
                    "someName3": "bla"
                }
            }
        }
    }
};

要创建它,我只有一些JSON,如下所示:

To create it, I only have some JSON such as the following:

{
    "rules": {
        "email": {
            "required": true,
            "email": true,
            "remote": {
                "url": "check-email.php",
                "type": "post",
                "data": {
                    "someName1": {"id":"someID1"},             
                    "someName2": {"id":"someID2"},             
                    "someName3": "bla"
                }
            }
        }
    }
}

{
    "rules": {
        "email": {
            "required": true,
            "email": true,
            "remote": {
                "url": "check-email.php",
                "type": "post",
                "data": {
                    "someName1": {"function":"return $( '#someID1' ).val()"},             
                    "someName2": {"function":"return $( '#someID2' ).val()"},             
                    "someName3": "bla"
                }
            }
        }
    }
}

或类似的东西。

如何实现这一目标?

推荐答案

您可以使用函数动态创建函数。假设你有第二个JSON结构:

You can use Function to create functions on the fly. Supposing you have the second JSON structure:

d = obj.rules.email.remote.data;
Object.keys(d).forEach(function(key) {
    d[key] = new Function(d[key].function); 
    //Note: You might want to check if d[key].function exists before using it.
});

这篇关于使用JSON中的方法创建JS对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆