gpt4 book ai didi

javascript - 使用javascript从数组创建一个对象

转载 作者:行者123 更新时间:2023-11-30 13:54:20 26 4
gpt4 key购买 nike

我有两个按顺序包含国家代码和货币的数组列表,但我需要知道如何组合并形成以下格式的对象。

var cn =["AL","DZ","AS","AD","AO","AI","AG","AR","AM","AW","AU"];
var ccy = ["ALL","DZD","USD","EUR","AOA","XCD","XCD","ARS","AMD","AWG","AUD"];

预期输出:

country:[
{
"code": "AL",
"currency": ["ALL"]
},
{
"code": "DZ",
"currency": ["DZD"]
}...
...
{
"code": "AU",
"currency": ["AUD"]
}
]

最佳答案

您可以使用 map 并使用 index 从第二个数组访问相应的值

var cn =["AL","DZ","AS","AD","AO","AI","AG","AR","AM","AW","AU"];
var ccy = ["ALL","DZD","USD","EUR","AOA","XCD","XCD","ARS","AMD","AWG","AUD"];

let final = cn.map((code,index)=>{
let currency = ccy[index]
return {code, currency: [currency]}
})

console.log(final)

关于javascript - 使用javascript从数组创建一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57600943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com