我打一個返回有各種貴重金屬,如投標價格的價格信息的JSON對象的API,問價,變化百分比,高/低,等從現有的JSON對象中構建新的JS對象的最佳方法是什麼?
我並不需要所有的屬性或對象內部的所有金屬類型,並且可能會出現我想循環對象的場景,所以我認爲只用我需要的屬性重新構建對象也許有意義。我很好奇最好的辦法是做什麼。
這裏是正在由API返回給我對象:
{
"gold_bid_usd_toz": "1286.32",
"gold_ask_usd_toz": "1287.32",
"gold_change_dollar_usd_toz": "5.72",
"gold_change_percent_usd_toz": "0.44%",
"gold_high_usd_toz": "1290.07",
"gold_low_usd_toz": "1277.01",
"gold_londonfix_am": "1278.44",
"gold_londonfix_pm": "1274.48",
"silver_bid_usd_toz": "17.2",
"silver_ask_usd_toz": "17.3",
"silver_change_dollar_usd_toz": "0.2",
"silver_change_percent_usd_toz": "1.17%",
"silver_high_usd_toz": "17.25",
"silver_low_usd_toz": "16.92",
"silver_londonfix": "16.69",
"platinum_bid_usd_toz": "924.75",
"platinum_ask_usd_toz": "929.75",
"platinum_change_dollar_usd_toz": "0.78",
"platinum_change_percent_usd_toz": "0.08%",
"platinum_high_usd_toz": "930.74",
"platinum_low_usd_toz": "920.5",
"platinum_londonfix_am": "914.03",
"platinum_londonfix_pm": "912.09",
"palladium_bid_usd_toz": "958.94",
"palladium_ask_usd_toz": "963.94",
"palladium_change_dollar_usd_toz": "-2.49",
"palladium_change_percent_usd_toz": "-0.26%",
"palladium_high_usd_toz": "967.31",
"palladium_low_usd_toz": "951.88",
"palladium_londonfix_am": "919.07",
"palladium_londonfix_pm": "919.01",
"englehard_fabricated_gold": "1199.21",
"englehard_fabricated_silver": "17.7000",
"usdcad": "1.248698",
"usdcny": "6.612501",
"xpt_xpd_timestamp": "1507075200000"
}
比方說,我只希望ask_usd_toz
,change_dollar_usd_toz
和change_percent_usd_toz
金,銀,鉑和鈀。
以下是一個很好的方法,只需要我需要的數據來構建一個新對象?
destructureObject(metal) {
const goldPrice = metal.gold_ask_usd_toz;
const goldChangeLastClose = metal.gold_change_dollar_usd_toz;
const goldPercentChange = metal.gold_change_percent_usd_toz;
const silverPrice = metal.silver_ask_usd_toz;
const silverChangeLastClose = metal.silver_change_dollar_usd_toz;
const silverPercentChange = metal.silver_change_percent_usd_toz;
const platinumPrice = metal.platinum_ask_usd_toz;
const platinumChangeLastClose = metal.platinum_change_dollar_usd_toz;
const platinumPercentChange = metal.platinum_change_percent_usd_toz;
const palladiumPrice = metal.palladium_ask_usd_toz;
const palladiumChangeLastClose = metal.palladium_change_dollar_usd_toz;
const palladiumPercentChange = metal.palladium_change_percent_usd_toz;
const metal = {
gold: {
goldPrice: goldPrice,
goldChangeLastClose: goldChangeLastClose,
goldPercentChange: goldPercentChange
},
silver: {
silverPrice: silverPrice,
silverChangeLastClose: silverChangeLastClose,
silverPercentChange: silverPercentChange
},
platinum: {
platinumPrice: platinumPrice,
platinumChangeLastClose: platinumChangeLastClose,
platinumPercentChange: platinumPercentChange
},
palladium: {
palladiumPrice: palladiumPrice,
palladiumChangeLastClose: palladiumChangeLastClose,
palladiumPercentChange: palladiumPercentChange
}
}
}
我覺得有一個更簡潔的方法來做到這一點。但也許不是。謝謝!
'JSON.parse(金屬);' – zer00ne
@ zer00ne你或許應該刪除評論。 – Archer