javascript - 多个数组对象操作

标签 javascript jquery json

array1 = [{"name":"John"},{"name":"James"}];
array2 = [{"gred_id":1,"name":"John","gred":"A"},{"gred_id":2,"name":"James","gred":"B"}];

我有 2 个像上面这样的数组。通过比较候选人的姓名,我想将 gred_id 放入 array1 中。我被困在这里了

$.each(array1,function(){
    var name= this["name"];

    $.each(array2, function(){
        if(name == this.name){
            this["grey_id"] = {"grey_id":this.id}; // not sure this is correct or wrong
        }
    });
});

这就是我最终想要的:

array1 = [{"name":"John","gred_id":1},{"name":"James","gred_id":2}];

最佳答案

根据 jQuery 的 .each() documentaion ,您不需要将该项存储在变量中。您可以使用 .each() 函数参数。第一个参数返回索引,第二个参数返回项目。

因此,您可以像这样优化代码。

Fiddle

var array1 = [{"name":"John"},{"name":"James"}];
var array2 = [{"gred_id":1,"name":"John","gred":"A"},{"gred_id":2,"name":"James","gred":"B"}];

$.each(array1, function (i, item) {
    $.each(array2, function (j, val) {
        if (item.name === val.name) {
            item.grey_id = val.gred_id;     
        }
    });
});

输出

array1 = [{"name":"John","gred_id":1},{"name":"James","gred_id":2}];

关于javascript - 多个数组对象操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32109842/

相关文章:

javascript - 由于 Node 的异步特性而导致问题需要帮助

javascript - 如何将内容div json的显示限制为三个

java - 使用 jqGrid 压缩 JSON

javascript - 显示 DataTables 中嵌套对象的集合

javascript - 使用 jQuery AJAX 请求 - POST 到 php

javascript - AngularJS 在 ng-repeat 循环中保留临时值

javascript - JavaScript 无法提取 CSS 值

javascript - canvas.toDataURL 导致纯黑色图像?

javascript - Gupshup Chat Web Widget 重定向问题

javascript - JS document.on 用于缓存元素