通过ID从对象中获取特定值

时间:2015-07-02 16:25:44

标签: javascript arrays json angularjs search

嗨,我有问题角度( like an object but with specific 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" }
];

3 个答案:

答案 0 :(得分:0)

您可以将filter与自定义搜索功能结合使用。在你的情况下,这个函数将是

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

Example in a fiddle

答案 1 :(得分: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);

答案 2 :(得分:0)

如果您使用的是angularJS:

super.show()

希望得到这个帮助。