Saya memiliki daftar mata uang di JSON yang datang seperti ini

{
    "USD": {
        "symbol": "$",
        "name": "US Dollar",
        "symbol_native": "$",
        "decimal_digits": 2,
        "rounding": 0,
        "code": "USD",
        "name_plural": "US dollars"
    },
    "CAD": {
        "symbol": "CA$",
        "name": "Canadian Dollar",
        "symbol_native": "$",
        "decimal_digits": 2,
        "rounding": 0,
        "code": "CAD",
        "name_plural": "Canadian dollars"
    },
}

Saya ingin memformat output jadi saya mendapatkannya seperti ini

[{name: "US Dolloar", symbol: "$"}, {name: "Canadian Dolloar", symbol: "CA$"} ]

Tapi aku merasa sulit melakukannya

  loadCurrencies() {
    this.http.get('assets/data/currencies.json').subscribe((response) => {
      this.currenciesList = response;
      console.log(this.currenciesList)
    })
  }
-1
neiza 8 Januari 2021, 19:44

3 jawaban

Jawaban Terbaik

Kode berikut akan membantu Anda.

const formattedData = Object.values(this.currenciesList).map(({ name, symbol }) => ({ name, symbol }))

console.log(formattedData)
2
jean-smaug 8 Januari 2021, 16:50

Berikut adalah salah satu pendekatan:

const data = {
  "USD": {
    "symbol": "$",
    "name": "US Dollar",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "USD",
    "name_plural": "US dollars"
  },
  "CAD": {
    "symbol": "CA$",
    "name": "Canadian Dollar",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "CAD",
    "name_plural": "Canadian dollars"
  },
}

const result = Object.values(data).map(({
  name,
  symbol
}) => ({
  name,
  symbol
}))

console.log(result)
1
Tibebes. M 8 Januari 2021, 16:50
loadCurrencies() {
    this.http.get('assets/data/currencies.json').subscribe((response) => {
        this.currenciesList = Object.values(response).map(obj =>
            return {
                name: obj.name,
                symbol: obj.symbol
            });
        console.log(this.currenciesList);
    });
}
0
Or Assayag 8 Januari 2021, 16:51