2015-07-02 124 views
-3

喜獲取從對象具體數值我有通過ID (like an object but with specific id)角度獲取對象的特定部分,真的,我不知道從哪裏開始解決它通過其ID

var Obj= [ 
      { Id: "1", shape: "circle", color: "red" }, 
      { Id: "2", shape: "square", color: "orange" }, 
      { Id: "3", shape: "triangle", color: "yellow" }, 
      { Id: "4", shape: "circle", color: "green" }, 
      { Id: "5", shape: "sphere", color: "blue" }, 
      { Id: "6", shape: "hexagon", color: "indigo" }, 
      { Id: "7", shape: "square", color: "violet" }, 
      { Id: "8", shape: "triangle", color: "red" } 
     ]; 

例如問題該功能必須是這樣的

和scope.result應該 像:

scope.result= [ 
{ Id: "3", shape: "triangle", color: "yellow" } 
]; 
+0

你的意思是像一個過濾器功能? 'Obj.filter(function(x){return x.Id == 3})' – maioman

+0

過濾器和forEach真的很好閱讀,我自己使用它們,但是你應該知道如果性能很重要(特別是大數據集例如),你不能擊敗for循環。特別是過濾器可能會慢25倍。 JSPerf關閉了垃圾郵件,否則我會在這裏發佈引用:-( – jme11

回答

0

如果您正在使用angularJS:

$scope.result = []; 
angular.forEach(Obj, function(value, key) { 
    if (value.Id == "3"){ 
     $scope.result.push(value); 
    } 
}); 
alert(angular.toJson($scope.result)); 

希望這有助於。

0

可以使用filter用自定義SE拱功能。在你的情況下,這個功能將是

function(e) { return e.Id == 3; } 

Example in a fiddle

0

我不是一個專家的角度,而是由一個ID(或任何其他值),你應該使用filter功能找到該項目。

下面是一個例子:

function getItemById(id, stack) { 
    // call the filter method 
    return stack.filter(function (item) { 
    // return `true` if the item.Id matches 
    return item.Id === id; 
    // take the first of possible multiple matches 
    // or `null` in case, there is no match 
    })[0] || null; 
} 

您可以使用此功能如下:

var result = getItemById('3', stack);