【问题标题】:Javascript - Comparing two arrays then pushing to new array on condition metJavascript - 比较两个数组,然后在满足条件时推送到新数组
【发布时间】:2016-07-26 12:58:42
【问题描述】:

有没有什么办法可以比较两个数组,如果满足条件则压入一个空数组?

假设我有一个对象数组。我需要遍历对象数组,获取 ID;然后将该 ID 与不同的数组进行比较。那么如果他们匹配将该数组中的一个值推送到一个空数组呢?

数组 1:

[{
    "addon_service": {
        "id": "f6f28cb5-78ad-4ec7-896d-16462b8202fd",
        "name": "papertrail"          
    },
    "app": {
        "id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2",
        "name": "mdda-mobiledocdelivery-stg"
    }
}]

数组 2

[{
    "app": {
        "id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2"
    },
    "stage": "staging",
}]

我需要将 Array 1 app.ID 与 Array 2 app.id 匹配。如果它们匹配,请检查应用程序处于哪个阶段(暂存、开发或生产)。然后将 Array 1 addon_service.name 推送到暂存开发或 生产数组取决于应用程序处于哪个阶段。我认为它很简单,只是无法理解它。

我认为这是一个措辞不当的问题。

【问题讨论】:

  • 以及应该如何查看生成的 空数组 ?
  • 看看Array.prototype.filter

标签: javascript arrays loops object


【解决方案1】:

您可以使用哈希表进行查找和舞台,并使用对象来收集匹配项。

var array1 = [{ "addon_service": { "id": "f6f28cb5-78ad-4ec7-896d-16462b8202fd", "name": "papertrail" }, "app": { "id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2", "name": "mdda-mobiledocdelivery-stg" } }],
    array2 = [{ "app": { "id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2" }, "stage": "staging", }],
    hash = Object.create(null),
    result = {};

array2.forEach(function (a) {
    hash[a.app.id] = a.stage;
});

array1.forEach(function (a) {
    if (hash[a.app.id]) {
        result[hash[a.app.id]] = result[hash[a.app.id]] || [];
        result[hash[a.app.id]].push(a.addon_service.name);
    }
})

console.log(result);

【讨论】:

    【解决方案2】:

    我认为这样就可以了。

    $.each(app1, function(key, value){
      $.each(app2, function(k, v){
        if(value.app.id == v.app.id){// find apps with the same `id`
          if(v[v.stage]){// check if the `stage` array already exists.
            v[v.stage].push(value.addon_service)
          }else{
             v[v.stage] = [value.addon_service];
          }
        }
      });
    });
    

    app1 是您问题中的第一个数组,app2 是第二个数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 2013-05-28
      • 1970-01-01
      • 2021-10-08
      相关资源
      最近更新 更多