简体   繁体   中英

Iterating over JSON put results into an Array

I have a JSON Object from a REST API like this:

{
  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
    }
  ]
};

I just want a list of the Currency values so am iterating over it like this:

var data = body.result;
for (var i in data) {
  var id = data[i].Currency;
  console.log(id)
}

Console prints ok:

GDP
USD
YEN

But I want to put these strings into a new Array and can't figure out how to do it. Any ideas?

Simply use the Array#Map function:

 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); 

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM