【问题标题】:How to convert two Array [closed]如何转换两个数组
【发布时间】:2018-10-31 02:35:59
【问题描述】:

什么是最好的转换方式:

["Isolated-1", "SVT_FedPortGroup", "SVT_StoragePortGroup", "VM Network", "test-pg-2002"]

还有这个:

["target_Isolated-1", "target_SVT_FedPortGroup", "target_SVT_StoragePortGroup","target_VM Network" ,"target_test-pg-2002"]; 

到:

"NetworkMaps": [
    {
        "ENVID": null,
        "SourcePG": "Isolated-1",
        "TargetPG": "target_Isolated-1"
    },
    {
        "ENVID": null,
        "SourcePG": "VM Network",
        "TargetPG": "target_SVT_FedPortGroup"
    }...
]

我需要将两个数组与各自的值合并。 例如

 arr1 : ["a", "b", "c"]; 
 arr2 : ["apple", "ball", "cat"];

result : [{source: "a",target: "apple"}, {source: "b",target: "ball"},{source: "c",target: "cat"}]

【问题讨论】:

  • 提供你迄今为止所做的努力?
  • 有很多资源可以做到这一点..请谷歌它..
  • 为什么VM Networktarget_SVT_FedPortGroup是同一个组?到目前为止你做了什么?
  • @Eddie VM Network 与 target_SVT_FedPortGroup 是同一组,因为键值。 [3] -> [3]

标签: javascript arrays angularjs json


【解决方案1】:

只需在一个简单的循环中按索引映射它们(如果它们具有相同的长度)。这是一个演示:

a = ["Isolated-1", "SVT_FedPortGroup", "SVT_StoragePortGroup", "VM Network", "test-pg-2002"]
b = ["target_Isolated-1", "target_SVT_FedPortGroup", "target_SVT_StoragePortGroup", "target_VM Network", "target_test-pg-2002"]
c = {
  "NetworkMaps": []
}
for (var i = 0; i < a.length; i++) {
  c.NetworkMaps.push({
    "ENVID": null,
    "SourcePG": a[i],
    "TargetPG": b[i]
  })
}
console.log(c);

【讨论】:

  • 感谢 Aleksey Solovey。长度始终相同。但是是否可以将它们与键值合并?例如:arr1.[0]和 arr2[0] , arr1.[1]和 arr2[1] ..etc?
  • @JeetPatel 看起来语法错误 (arr1.[0])。您也可以使用 c.NetworkMaps = a.map((e,i) =&gt; {return {"ENVID":null, "SourcePG":e, "TargetPG":b[i]}}) 映射它们而不使用数组
  • 它为我工作。但我认为我应该以不同的方式处理它。再次感谢 Aleksey Solovey。
  • @JeetPatel 尝试用描述你的问题而不是attempted solution来提问
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
  • 1970-01-01
相关资源
最近更新 更多