我得到了带有rest api的对象,我想将其转换为类似的内容:
获取对象:
{
"base":"PLN",
"rates":{
"USD":0.2645340686,
"EUR":0.2336666978
},
"date":"2019-04-12"
}
我需要转换为:
[
{
"currency": "USD",
"currency_exchange_rate": 0.264534068,
"date_currency_exchange_rate_sync": "2019-04-12"
},
{
"currency": "EUR",
"currency_exchange_rate": 0.2336666978,
"date_currency_exchange_rate_sync": "2019-04-12"
}
]
答案 0 :(得分:1)
这很简单。您可以使用Object.keys
和map
来创建此转换。
Object.keys(obj.rates).map(rate => {
return {
"currency":rate,
"currency_exchange_rate":obj.rates[rate],
"date_currency_exchange_rate_sync":obj.date
}
})
答案 1 :(得分:1)
您可以映射rate
的条目并获取日期。
var object = { base:"PLN", rates: { USD: 0.2645340686, EUR: 0.2336666978 }, date: "2019-04-12" },
array = Object
.entries(object.rates)
.map(([currency, currency_exchange_rate]) => ({
currency,
currency_exchange_rate,
date_currency_exchange_rate_sync: object.date
}));
console.log(array);
答案 2 :(得分:0)
您可以反对利率以获得键/值对,而不是映射
let obj = {
"base":"PLN",
"rates":{
"USD":0.2645340686,
"EUR":0.2336666978
},
"date":"2019-04-12"
}
let op = Object.entries(obj.rates).map(([currency,rate])=> ({
currency,
"currency_exchange_rate": rate,
"date_currency_exchange_rate_sync": obj.date
}))
console.log(op)
答案 3 :(得分:0)
还有另一个使用JSONata表达式的答案:
$each($.rates, function($v, $k){
{
"currency": $k,
"currency_exchange_rate": $v,
"date_currency_exchange_rate_sync": $.date
}
})