如何使用angularjs在id相同的json数组中获取另一个对象

时间:2016-02-11 12:24:54

标签: javascript angularjs json

在填写表单时,我发送了closedBy所选项目的ID

if (selectedClosedPlaces != undefined) {
            place.closedBy = selectedClosedPlaces.map(function(g) {
                return g._id;
            });
        } else {
            place.closedBy = ['no_name'];
        }

我使用{{place.closedBy}}在html中显示它。
我将拥有像这样的json数据

[{"_id":"56bc720bd0113ab80dd3cb2d","name":{"en":"fshu","de":"hfasj"},"closedBy":["no_name"],"category":{"_id":"56bb2999f197db040dc3b12b","name":{"en":"asdfdsf","de":"asdf"}}}},
{"_id":"56bc7238d0113ab80dd3cb2e","name":{"en":"jsfadk","de":"jkgdj"},"closedBy":["56bc720bd0113ab80dd3cb2d"],"category":{"_id":"56bb2999f197db040dc3b12b","name":{"en":"asdfdsf","de":"asdf"}}}}]

对于第一个,它将为null,所以我给了一些像['no_name']这样的名字。添加第一个后,我可以使用selectbox选择closedBy。
现在我正在为第二个人归来。我正在使用封闭的第二个id,请检查上面的json。有了那个id,我需要获取那个特定的名字 示例:我拥有此{id} 56bc720bd0113ab80dd3cb2d ID我需要显示name.en和name.de => fshu and hfasj。 我正在使用服务来获取值   //此处的服务代码

.service('PlaceService', function($http) {
    return {
        init: function(callback) {
            $http.get('/api/places').then(function(place_response) {
                callback(place_response);
            });
        }
    }
})

并在控制器中

PlaceService.init(function(place_response) {
            $scope.places = place_response.data;
        console.log($scope.places); //giving all the places details like the //above json.
       console.log($scope.places.closedBy); // Not giving closedBy value here

任何人都可以帮助我

1 个答案:

答案 0 :(得分:1)

找到另一个第一个项,在对象数组中有特定的id,你可以使用_underscore js lib,如下所示:

var yourWantedId = ...;    
var result = _.findWhere(selectedClosedPlaces, {"_id": yourWantedId });