gpt4 book ai didi

javascript - 在 Angular 中使用下划线在数组中查找内容

转载 作者:行者123 更新时间:2023-12-03 12:35:31 25 4
gpt4 key购买 nike

我正在开发一个 Angular 项目,在该项目中我可以访问用户数据的 JSON feed。通常,我会通过简单地执行以下操作将其称为 Controller 中的服务:

userFactory.get(function (data) {
$scope.results = data;
}

但是,在我的一个 Controller 中,我需要编写一个 if 语句来检查嵌套数组,以查看 type 字段是否具有特定值。在下面的示例中,我正在查找 "type": "yep"

{
   "id": 3,
"data": stuff,
   "following": [
      {
         "id": 213,
         "type": "nope",
      },
      {
         "id": 324,
         "type": "nope",
      },
      {
         "id": 532,
         "type": "yep",
      }
   ],
}

我需要做的是搜索以下对象以查找是否存在 "type": "yep" 的实例。我认为这可以用下划线实现,但我不确定如何实现。我在想一些类似的事情:

userFactory.get(function (user) {
$scope.user=user;
if (underscore find if value exsist){
// do stuff
}
else
{
//do other stuff
}
)};

想法?

最佳答案

var data = {
"id": 3,
"data": 'stuff',
"following": [{
"id": 213,
"type": "nope",
}, {
"id": 324,
"type": "nope",
}, {
"id": 532,
"type": "yep",
}],
};
var result = _.find(data.following, function (item) {
return item.type === "yep";
});
if(result)
console.log(result);
else
//do your stuff.

<强> Fiddle

关于javascript - 在 Angular 中使用下划线在数组中查找内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23750418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com