program story

AngularJS의 객체 배열에서 id로 특정 객체를 가져옵니다.

inputbox 2020. 8. 2. 18:35
반응형

AngularJS의 객체 배열에서 id로 특정 객체를 가져옵니다.


AngularJS 웹 사이트에서 액세스하고 싶은 데이터가 포함 된 JSON 파일이 있습니다. 이제 내가 원하는 것은 배열에서 하나의 객체 만 얻는 것입니다. 예를 들어 id가 1 인 Item을 좋아합니다.

데이터는 다음과 같습니다.

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

다음과 같이 AngularJS $ http 기능을 사용하여 데이터를로드하고 싶습니다.

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

작동합니다. 그러나 이제 내가 얻는 배열에서 특정 데이터 객체를 id로 $http.get어떻게 얻을 수 있습니까?

도움을 주셔서 감사합니다.

마크 접견


이를 수행하는 유일한 방법은 배열을 반복하는 것입니다. 분명히 결과가 ID별로 정렬되어 있다고 확신하면 이진 검색을 수행 할 수 있습니다


ES6 솔루션 사용

이 답변을 여전히 읽는 사람들을 위해 ES6을 사용하는 경우 find메소드가 배열에 추가되었습니다. 따라서 동일한 컬렉션을 가정하면 솔루션은 다음과 같습니다.

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

각도 또는 다른 프레임 워크에 덜 묶여 있으므로이 솔루션을 완전히 사용하려고합니다. 순수한 자바 스크립트.

각도 솔루션 (구 솔루션)

나는 다음을 수행 하여이 문제를 해결하는 것을 목표로했다.

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

사용 사례 :

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);
}]);

플 런커 : http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview


이 오래된 게시물을 보는 사람에게는 이것이 현재 가장 쉬운 방법입니다. AngularJS 만 필요합니다 $filter. 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" }

경고

@mpgn이 말했듯이 이것은 제대로 작동하지 않습니다 . 더 많은 결과를 얻을 수 있습니다. 예 : 3을 검색하면 23도 잡습니다.


개인적으로 나는 이런 종류의 물건에 밑줄을 사용합니다 ... 그래서

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

"a"는 id가 2 인 배열에서 원하는 행입니다.


Willemoes 에 뭔가를 추가하고 싶습니다 . HTML 안에 직접 작성된 동일한 코드는 다음과 같습니다.

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

"results"가 FooController의 변수이고 필터링 된 항목의 "name"속성을 표시하려고한다고 가정합니다.


예를 들어 ng-repeat사용하려는 데이터와 데이터가 일치하는 경우에만 데이터를 사용 하고 선택할 수 있습니다 ng-show.

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

배열을 반복 할 수 있습니다.

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);

이 지저분한 루프를 작성하지 않으려면 underscore.js 또는 Lo-Dash (후자의 예)를 사용하는 것이 좋습니다 .

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

state id를 기준으로 city와 같은 항목 목록을 원하면

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

불행히도 (실수하지 않은 한) 결과 개체를 반복해야한다고 생각합니다.

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

최소한이 방법으로 올바른 일치 ID를 찾으면 반복에서 벗어날 수 있습니다.


왜 상황이 복잡합니까? 이것은 다음과 같은 간단한 함수를 작성합니다.

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 '';
}

사용 사례 :

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'));

산출:

Result is Bərdə filialı

$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>

출력 : Azərbaycan


가능하면 배열 색인을 ID로 사용하여 JSON 데이터 구조를 설계하십시오. RDBMS와 같이 배열 인덱스를 "기본 키"및 "외부 키"로 사용하는 데 문제가없는 한 JSON 배열을 "정규화"할 수도 있습니다. 따라서 앞으로는 다음과 같이 할 수도 있습니다.

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

이것이 "By Design" 솔루션 입니다. 귀하의 경우 간단히 :

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; 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:

$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:

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

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

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. 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.


use $timeout and run a function to search in "results" array

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:

var foundResultObject = getObjectFromResultsList(results, 1);

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

참고URL : https://stackoverflow.com/questions/19590063/get-specific-object-by-id-from-array-of-objects-in-angularjs

반응형