javascript - 在推送项目之前检查属性值是否存在

标签 javascript angularjs arrays

下面是我的示例代码,它通过检查项目是否不存在来推送到 VacanciesWithSavedSearches 数组。

 if ($scope.VacanciesWithSavedSearches.indexOf(value) == -1) {

            $scope.VacanciesWithSavedSearches.push({
                type: "Saved Searches",
                title: value.title,
                value: value.id
            });
        }

如何通过将 indexOf 替换为实际属性值来更改上述内容,例如,如果列表不包含其他项目,则将项目添加到列表 VacanciesWithSavedSearches.id=123

最佳答案

使用array.filter

var result = $scope.VacanciesWithSavedSearches.filter(t=t.id ==='123');
if(result.length === 0)
{
  $scope.VacanciesWithSavedSearches.push({
     type: "Saved Searches",
     title: value.title,
     value: value.id
   });          

}

关于javascript - 在推送项目之前检查属性值是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46241931/

相关文章:

arrays - 加入 Elasticsearch 索引,同时匹配嵌套/内部对象中的字段

javascript - SpeechSynthesis - Onend 在语音结束前触发

javascript - angularjs `$digest`什么时候触发?

javascript - AngularJS:从第三方库访问工厂或服务

javascript - 使用下拉菜单过滤 ng-repeat 而不复制下拉选项

javascript - 在 JavaScript 中将数组排序为 "rows"

c - 函数中返回文件/文件夹结构的指针

javascript - 影响其他 Div 宽度的动态 Div 宽度

javascript - Item 上的 Canvas 鼠标移动事件

javascript - Node.js - 如何从模块中找出类/对象的属性?