4

我在这里遇到了一个令人费解的问题,我使用 Backbone 中的集合检索了一个 JSON 对象。这是对象的样子:

{
    "MatchID": "00000001",
    "Date": "1970-01-01T00:00:00.000Z",
    "OriginalID": "",
    "Stage": {
        "StageNumber": "0",
        "StageType": "Stage Type"
    },
    "Round": {
        "RoundNumber": "0",
        "Name": "Round Name"
    },
    "Leg": "1",
    "HomeTeam": {
        "TeamID": "0",
        "Name": "Home Team Name"
    },
    "AwayTeam": {
        "TeamID": "0",
        "Name": "Away Team Name"
    },
    "Venue": {
        "VenueID": "0",
        "Name": "Venu Name"
    },
    "Referee": null,
}

我想对这些数据做些什么,是根据特定属性过滤它,例如 Venue.Name 或 Date 属性(它们是对象的不同深度,对于其他一些数据,可能比两个级别更深) . 我在 Backbone 集合中有以下代码来过滤并返回一个新集合,其中的内容经过适当过滤:

findWhere: function (Attribute, Value)
{
    return new Project.Collections.Fixtures(this.filter(function (fixture)
    {
        return eval('fixture.attributes.' + Attribute) == Value;
    }));
}

这允许我在一个属性中指定我想要过滤的属性,以及我希望它等于什么,对于任何深度的对象。问题是,我真的不想使用“eval”来执行此操作,但显然我不能将“[Attribute]”用于“AwayTeam.TeamID”之类的东西,因为它不起作用。

有谁知道我可以在不使用 eval 的情况下实现此功能的方法?

4

4 回答 4

9

像这样的东西会让你遍历对象的层次结构来找到一个值:

var x = {
    y: {
        z: 1
    }
};

function findprop(obj, path) {
    var args = path.split('.'), i, l;

    for (i=0, l=args.length; i<l; i++) {
        if (!obj.hasOwnProperty(args[i]))
            return;
        obj = obj[args[i]];
    }

    return obj;
}

findprop(x, 'y.z');

您可以将此作为方法添加到您的Fixture对象:

Fixture = Backbone.Model.extend({
    findprop: function(path) {
        var obj = this.attributes,
            args = path.split('.'), 
            i, l;

        for (i=0, l=args.length; i<l; i++) {
            if (!obj.hasOwnProperty(args[i]))
                return;
            obj = obj[ args[i] ];
        }
        return obj;
    }
});

并用它来提取价值

var f = new Fixture();
f.findprop("HomeTeam.TeamID");

然后该findWhere方法可以重写为

findWhere: function (Attribute, Value)
{
    return new Project.Collections.Fixtures(this.filter(function (fixture){
        return fixture.findprop(Attribute) === Value;
    }));
}

还有一个可以玩的小提琴http://jsfiddle.net/nikoshr/wjWVJ/3/

于 2012-05-29T13:14:28.853 回答
1

JavaScript 对象中的属性可以通过方括号、字符串标识符以及标准的点符号来访问。

换句话说,这:

fixture.attributes.something

与此相同:

fixture.attributes["something"]

您还可以将变量名称传递到方括号中,变量的值用作检索的键。

因此,您可以将代码更改为:

findWhere: function (Attribute, Value)
{
    return new Project.Collections.Fixtures(this.filter(function (fixture)
    {
        return fixture.attributes[Attribute] === Value;
    }));
}

正如您在评论中指出的那样,这只处理一级对象和属性。要获取嵌套属性,您需要拆分“属性”变量并循环访问各个部分。我喜欢@nikoshr 的解决方案。

于 2012-05-29T13:16:43.553 回答
1

像这样使用怎么eval()样:

var myObject = {
  
  first: 'Some',
  last: 'Person',
  
  address: {
    city: 'Melbourne',
    country: 'Australia'
  }

}

var propPath = 'address.city';

var city = eval("myObject."+propPath);

console.log(city); // = Melbourne

于 2014-11-21T03:42:14.007 回答
0

我接受了 nikoshr 的回答,并为其添加了一些递归风格:

  var findprop = function (obj, path) {
        var args = (typeof path === 'string') ? path.split('.') : path,
            thisProperty = obj[args[0]];
        if (thisProperty === undefined) { return; } //not found

        args.splice(0, 1); //pop this off the array

        if (args.length > 0) { return findprop(thisProperty, args); } //recurse
        else {return thisProperty; }
    };

我不确定递归 cpu 循环是否有很多好处,但我喜欢递归函数在合适的时候

于 2012-08-17T15:29:20.410 回答