我有一个来自 REST API 的 JSON 对象,如下所示:
{
success: true,
message: "",
result: [{
Currency: "GBP",
IsActive: true,
BaseAddress: "1N52wHoVR79PMDishab2XmRHsbekCdGquK",
Notice: null
},
{
Currency: "USD",
IsActive: true,
BaseAddress: "LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx",
Notice: null
},
{
Currency: "YEN",
IsActive: true,
BaseAddress: "D9GqmkGCpgtnXP7xMD78v9xfqeDkqBZBMT",
Notice: null
}
]
};
我只想要一个货币值列表,所以我像这样迭代它:
var data = body.result;
for (var i in data) {
var id = data[i].Currency;
console.log(id)
}
控制台打印正常:
GDP
USD
YEN
但是我想将这些字符串放入一个新的数组中,但不知道该怎么做。有任何想法吗?
最佳答案
只需使用 Array#Map
函数:
const data = {
success: true,
message: "",
result: [{
Currency: "GBP",
IsActive: true,
BaseAddress: "1N52wHoVR79PMDishab2XmRHsbekCdGquK",
Notice: null
},
{
Currency: "USD",
IsActive: true,
BaseAddress: "LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx",
Notice: null
},
{
Currency: "YEN",
IsActive: true,
BaseAddress: "D9GqmkGCpgtnXP7xMD78v9xfqeDkqBZBMT",
Notice: null
},
{
Currency: "YEN",
IsActive: true,
BaseAddress: "D9GqmkGCpgtnXP7xMD78v9xfqeDkqBZBMT",
Notice: null
}
]
}
const currencies = [...new Set(data.result.map(a => a.Currency))];
console.log(currencies);
关于javascript - 迭代 JSON 将结果放入数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45731101/