2015-07-02 77 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);