arrays - angularjs 比较两个数组

标签 arrays angularjs

如何在 AngularJS 中比较两个数组并返回匹配的值?

这是第一个数组:

[{
    "id":2,
    "student_name":"LiSa",
    "alien":"A",
    "world":"Sun",
    "justification":"i like sent this one",
    "submit_time":null
},{
    "id":1,
    "student_name":"Liz",
    "alien":"B",
    "world":"Earth",
    "justification":null,
    "submit_time":"2014-09-25T08:37:34.526-05:00"
}]

这是第二个:

[{
    "id":1,
    "alien":"A",
    "world":"Sun",
    "color":"red"
},{
    "id":2,
    "alien":"A",
    "world":"Mercury",
    "color":"red"
},{
    "id":3,
    "alien":"B",
    "world":"Earth",
    "color":"red"
},{
    "id":4,
    "alien":"B",
    "world":"Moon",
    "color":"red"
}]

我想检查这两个数组中的 alienworld 值是否匹配。然后我可以从第二个数组中获取颜色值。

这是我放入 Controller 中的代码:

angular.forEach(arr1, function(value1, key1) {
    angular.forEach(arr2, function(value2, key2){
        if(value1.alien === value2.alien && value1.world === value2.world){
            console.log(value2.color);

        }
    });
});

我应该使用angular.forEach吗?我怎样才能做到这一点?我在哪里存储颜色值?

最佳答案

就像邓肯所说,这些都是对象数组,而不是多维数组。这里我使用 Angulars .forEach 方法循环遍历两个数组,然后比较对象属性。

我添加了一条评论,您可以在其中获得匹配的颜色。

angular.forEach(arr1, function(value1, key1) {
    angular.forEach(arr2, function(value2, key2) {
        if (value1.alien === value2.alien && value1.world === value2.world) {
            // here is where you grab the value2.color
        }
    });
});

这是一个fiddle

关于arrays - angularjs 比较两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29133885/

相关文章:

javascript - 对数组中对象数据的更改/编辑列表进行排序

java - 将通用列表转换为 java 对象

javascript - angular ui 错误 : $modal. open is not a function

html - 带有盒子的 ionic 和电话间隙中的CSS

javascript - View 的更改不会更新模型范围变量

javascript - Karma + Angular 模拟 TypeError : 'undefined' is not an object (evaluating 'angular.mock = {}' )

java - 如何创建一个由用户输入定义长度的静态数组?

c++ - 我不知道如何让我的程序使用局部变量而不是全局变量

c# - 如何在逐字节读取 CSV 文件时检测字节是否为换行符 - C#

html - 用户个人资料照片, Angular 落有可点击图标以上传照片 - html