我有一个来自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
但是我想将这些字符串放入一个新的数组中,并且无法弄清楚如何做到这一点。有什么想法吗?
答案 0 :(得分:6)
只需使用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);
答案 1 :(得分:0)
var body = {
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 res = body.result.map(item => { return item.Currency });
console.log(res);