简体   繁体   English

从AngularJS中的对象数组中通过id获取特定对象

[英]Get specific object by id from array of objects in AngularJS

I have a JSON file containing some data I d like to access on my AngularJS website. 我有一个JSON文件,其中包含我想在AngularJS网站上访问的一些数据。 Now what I want is to get only one object from the array. 现在我想要的是从数组中只获取一个对象。 So I d like for example Item with id 1. 所以我想要例如ID为1的Item。

The data looks like this: 数据如下所示:

{ "results": [
    {
        "id": 1,
        "name": "Test"
    },
    {
        "id": 2,
        "name": "Beispiel"
    },
    {
        "id": 3,
        "name": "Sample"
    }
] }

I d like to load the data with AngularJS $http functionality like this: 我想用AngularJS $ http功能加载数据,如下所示:

$http.get("data/SampleData.json");

which is working. 这是有效的。 But how can I now get a specific data object (by id) from the array I get from $http.get ? 但是,我现在如何从$http.get获得的数组中获取特定的数据对象(通过id)?

Thanks in advance for your help. 在此先感谢您的帮助。

Greets Marc 迎接马克

Using ES6 solution 使用ES6解决方案

For those still reading this answer, if you are using ES6 the find method was added in arrays. 对于仍在阅读此答案的人,如果您使用的是ES6,则会在数组中添加find方法。 So assuming the same collection, the solution'd be: 所以假设相同的集合,解决方案是:

const foo = { "results": [
    {
        "id": 12,
        "name": "Test"
    },
    {
        "id": 2,
        "name": "Beispiel"
    },
    {
        "id": 3,
        "name": "Sample"
    }
] };
foo.results.find(item => item.id === 2)

I'd totally go for this solution now, as is less tied to angular or any other framework. 我现在完全采用这种解决方案,因为它与角度或任何其他框架无关。 Pure Javascript. 纯Javascript。

Angular solution (old solution) 角度解决方案(旧解决方案)

I aimed to solve this problem by doing the following: 我的目标是通过执行以下操作来解决此问题:

$filter('filter')(foo.results, {id: 1})[0];

A use case example: 一个用例示例:

app.controller('FooCtrl', ['$filter', function($filter) {
    var foo = { "results": [
        {
            "id": 12,
            "name": "Test"
        },
        {
            "id": 2,
            "name": "Beispiel"
        },
        {
            "id": 3,
            "name": "Sample"
        }
    ] };

    // We filter the array by id, the result is an array
    // so we select the element 0

    single_object = $filter('filter')(foo.results, function (d) {return d.id === 2;})[0];

    // If you want to see the result, just check the log
    console.log(single_object);
}]);

Plunker: http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview Plunker: http ://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p =preview

For anyone looking at this old post, this is the easiest way to do it currently. 对于任何看过这篇旧帖子的人来说,这是目前最简单的方法。 It only requires an AngularJS $filter . 它只需要一个AngularJS $filter Its like Willemoes answer, but shorter and easier to understand. 它像Willemoes的答案,但更短,更容易理解。

{ 
    "results": [
        {
            "id": 1,
            "name": "Test"
        },
        {
            "id": 2,
            "name": "Beispiel"
        },
        {
            "id": 3,
            "name": "Sample"
        }
    ] 
}

var object_by_id = $filter('filter')(foo.results, {id: 2 })[0];
// Returns { id: 2, name: "Beispiel" }

WARNING 警告

As @mpgn says, this doesn't work properly . 正如@mpgn所说,这不能正常工作 This will catch more results. 这将获得更多结果。 Example: when you search 3 this will catch 23 too 示例: 当您搜索3时,这也将捕获23

personally i use underscore for this kind of stuff... so 我个人用下划线来表达这种东西......所以

a = _.find(results,function(rw){ return rw.id == 2 });

then "a" would be the row that you wanted of your array where the id was equal to 2 然后“a”将是你想要的数组的行,其中id等于2

I just want to add something to Willemoes answer . 我只是想对Willemoes的回答添加一些东西。 The same code written directly inside the HTML will look like this: 直接在HTML中编写的相同代码如下所示:

{{(FooController.results | filter : {id: 1})[0].name }}

Assuming that "results" is a variable of your FooController and you want to display the "name" property of the filtered item. 假设“results”是您的FooController的变量,并且您希望显示已过滤项的“name”属性。

You can use ng-repeat and pick data only if data matches what you are looking for using ng-show for example: 您可以使用ng-repeat和挑选的数据只有当数据匹配你在找什么用ng-show ,例如:

 <div ng-repeat="data in res.results" ng-show="data.id==1">
     {{data.name}}
 </div>    

You can just loop over your array: 你可以循环遍历你的数组:

var doc = { /* your json */ };

function getById(arr, id) {
    for (var d = 0, len = arr.length; d < len; d += 1) {
        if (arr[d].id === id) {
            return arr[d];
        }
    }
}

var doc_id_2 = getById(doc.results, 2);

If you don't want to write this messy loops, you can consider using underscore.js or Lo-Dash (example in the latter): 如果你不想编写这个凌乱的循环,你可以考虑使用underscore.jsLo-Dash (后者的例子):

var doc_id_2 = _.filter(doc.results, {id: 2})[0]

If you want the list of items like city on the basis of state id then use 如果你想要基于状态id的城市项目列表然后使用

var state_Id = 5;
var items = ($filter('filter')(citylist, {stateId: state_Id }));

Unfortunately (unless I'm mistaken), I think you need to iterate over the results object. 不幸的是(除非我弄错了),我认为你需要迭代结果对象。

for(var i = 0; i < results.length; i += 1){
    var result = results[i];
    if(result.id === id){
        return result;
    }
}

At least this way it will break out of the iteration as soon as it finds the correct matching id. 至少这样一旦找到正确的匹配id,它就会突破迭代。

Why complicate the situation? 为什么情况复杂化? this is simple write some function like this: 这很简单,写一些这样的函数:

function findBySpecField(data, reqField, value, resField) {
    var container = data;
    for (var i = 0; i < container.length; i++) {
        if (container[i][reqField] == value) {
            return(container[i][resField]);
        }
    }
    return '';
}

Use Case: 使用案例:

var data=[{
            "id": 502100,
            "name": "Bərdə filialı"
        },
        {
            "id": 502122
            "name": "10 saylı filialı"
        },
        {
            "id": 503176
            "name": "5 sayli filialı"
        }]

console.log('Result is  '+findBySpecField(data,'id','502100','name'));

output: 输出:

Result is Bərdə filialı

The only way to do this is to iterate over the array. 执行此操作的唯一方法是迭代数组。 Obviously if you are sure that the results are ordered by id you can do a binary search 显然,如果你确定结果是按id排序的,你可以进行二进制搜索

$scope.olkes = [{'id':11, 'name':'---Zəhmət olmasa seçim edin---'},
                {'id':15, 'name':'Türkyə'},
                {'id':45, 'name':'Azərbaycan'},
                {'id':60, 'name':'Rusya'},
                {'id':64, 'name':'Gürcüstan'},
                {'id':65, 'name':'Qazaxıstan'}];

<span>{{(olkes | filter: {id:45})[0].name}}</span>

output: Azərbaycan 输出:Azərbaycan

If you can, design your JSON data structure by making use of the array indexes as IDs. 如果可以,可以通过将数组索引用作ID来设计JSON数据结构。 You can even "normalize" your JSON arrays as long as you've no problem making use of the array indexes as "primary key" and "foreign key", something like RDBMS. 只要您将数组索引用作“主键”和“外键”(如RDBMS)就没有问题,您甚至可以“规范化”JSON数组。 As such, in future, you can even do something like this: 因此,将来你甚至可以这样做:

function getParentById(childID) {
var parentObject = parentArray[childArray[childID].parentID];
return parentObject;
}

This is the solution "By Design" . 这是“按设计”的解决方案。 For your case, simply: 对于您的情况,只需:

var nameToFind = results[idToQuery - 1].name;

Of course, if your ID format is something like "XX-0001" of which its array index is 0 , then you can either do some string manipulation to map the ID; 当然,如果您的ID格式类似于“XX-0001” ,其数组索引为0 ,那么您可以执行一些字符串操作来映射ID; or else nothing can be done about that except through the iteration approach. 除非通过迭代方法,否则无法做任何事情。

I know I am too late to answer but it's always better to show up rather than not showing up at all :). 我知道我来不及回答,但总是更好地出现而不是完全露面:)。 ES6 way to get it: ES6方式得到它:

$http.get("data/SampleData.json").then(response => {
let id = 'xyz';
let item = response.data.results.find(result => result.id === id);
console.log(item); //your desired item
});

The simple way to get (one) element from array by id: 通过id从数组中获取(one)元素的简单方法:

The find() method returns the value of the first element in the array that satisfies the provided testing function. find()方法返回数组中第一个满足提供的测试函数的元素的值。 Otherwise undefined is returned. 否则返回undefined。

function isBigEnough(element) {
    return element >= 15;
}

var integers = [12, 5, 8, 130, 160, 44];
integers.find(isBigEnough); // 130  only one element - first

you don't need to use filter() and catch first element xx.filter()[0] like in comments above 你不需要使用filter()并像上面的注释一样捕获第一个元素xx.filter()[0]

The same for objects in array 对于数组中的对象也是如此

var foo = {
"results" : [{
    "id" : 1,
    "name" : "Test"
}, {
    "id" : 2,
    "name" : "Beispiel"
}, {
    "id" : 3,
    "name" : "Sample"
}
]};

var secondElement = foo.results.find(function(item){
    return item.id == 2;
});

var json = JSON.stringify(secondElement);
console.log(json);

Of course if you have multiple id then use filter() method to get all objects. 当然,如果你有多个id,那么使用filter()方法来获取所有对象。 Cheers 干杯

 function isBigEnough(element) { return element >= 15; } var integers = [12, 5, 8, 130, 160, 44]; integers.find(isBigEnough); // 130 only one element - first 

 var foo = { "results" : [{ "id" : 1, "name" : "Test" }, { "id" : 2, "name" : "Beispiel" }, { "id" : 3, "name" : "Sample" } ]}; var secondElement = foo.results.find(function(item){ return item.id == 2; }); var json = JSON.stringify(secondElement); console.log(json); 

    projectDetailsController.controller('ProjectDetailsCtrl', function ($scope, $routeParams, $http) {
    $http.get('data/projects.json').success(function(data) {

        $scope.projects = data;
        console.log(data);

        for(var i = 0; i < data.length; i++) {
        $scope.project = data[i];
        if($scope.project.name === $routeParams.projectName) {
            console.log('project-details',$scope.project);
        return $scope.project;
        }
        }

    });
});

Not sure if it's really good, but this was helpful for me.. I needed to use $scope to make it work properly. 不确定它是否真的很好,但这对我有用..我需要使用$ scope来使其正常工作。

use $timeout and run a function to search in "results" array 使用$ timeout并运行一个函数来搜索“results”数组

app.controller("Search", function ($scope, $timeout) {
        var foo = { "results": [
          {
             "id": 12,
             "name": "Test"
          },
          {
             "id": 2,
             "name": "Beispiel"
          },
          {
             "id": 3,
            "name": "Sample"
          }
        ] };
        $timeout(function () {
            for (var i = 0; i < foo.results.length; i++) {
                if (foo.results[i].id=== 2) {
                    $scope.name = foo.results[i].name;
                }
            }
        }, 10);

    });

I would iterate over the results array using an angularjs filter like this: 我会使用angularjs过滤器迭代结果数组,如下所示:

var foundResultObject = getObjectFromResultsList(results, 1); var foundResultObject = getObjectFromResultsList(results,1);

function getObjectFromResultsList(results, resultIdToRetrieve) {
        return $filter('filter')(results, { id: resultIdToRetrieve }, true)[0];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM