4

我有:

    businesses: [
    {businessName: 'A', "address":[loc1, loc2, loc3]},
    {businessName: 'B', "address":[loc1, loc2]},
    {businessName: 'C', "address":[loc1]}
};

我想用输出重复这个对象:

A | street, city, zip, state 
A | street, city, zip, state 
A | street, city, zip, state 
B | street, city, zip, state 
B | street, city, zip, state 
C | street, city, zip, state 

换句话说,我想在带有 ng-repeat 的表格中将此对象显示为平面。

我必须自己将其展平,还是 ng-repeat 有能力做到这一点?

理想情况下,我可以做类似的事情

ng-repeat business in businesses
business.businessName | business.address.City | business.address.State

通过指定地址,它应该知道我想要它们。

否则,我如何扁平化这样的对象?

谢谢!

4

2 回答 2

4

似乎您可以对其进行一些处理,例如:

var flatBusinesses = [];
for (business in businesses) {
    for (address in business.addresses) {
        flatBusinesses.push ({name: business.name, address: address.City, state: address.State}
    }
}

然后在视图中重复 flatBusinesses

于 2013-06-12T22:14:19.367 回答
3

underscore 库有许多处理 javascript 数组和对象的函数,它们可以很好地作为 angular 的补充:

http://underscorejs.org/

您需要下载该库并将其添加到您的项目中。

然后你可以写:

var flatBusinesses = _.flatten(_.pluck(businesses, 'address'));

您应该能够将下划线库添加到范围:

$scope._ = _;

然后将其直接添加到您的模板中:

<div ng-repeat="business in _.flatten(_.pluck(businesses, 'address'))">
{{business.businessName}} | {{business.address.City}} | {{business.address.State}}
</div>

编辑:

所以,我没有足够仔细地阅读你的问题,在你的情况下,扁平化和采摘不会削减它。

我用下划线拼凑了一个小提琴来使它工作,但最终的结果并没有比 rquinn 的响应有所改进。

无论如何,如果你想看的话,这里是小提琴:http: //jsfiddle.net/pna7f5h3/

于 2013-06-12T22:40:20.307 回答