如何解决一排到四排
[{
"coin": "AION","profit": "3.10","timestamp": "2021-01-26 00:48:01"
},{
"coin": "BTC","profit": "77.00","timestamp": "2021-01-26 00:08:04"
},{
"coin": "AION","profit": "4.00","timestamp": "2021-01-26 01:08:01"
},"profit": "78.10","timestamp": "2021-01-26 01:08:04"
}]
但我实际需要的是四个(四个是可变的)数组:
array coins:
[{ "AION","BTC" }]
(variable with extra coins,depending on the first array i already have) > AION,BTC,ETH,ZIL,ARK,etc....
array profit[AION]:
[{ "3.10","4.00" }]
array profit[BTC]:
[{ "77.00","78.10" }]
(Variable extra coins/profits) [ETH,etc...]
array timestamp:
[{ "2021-01-26 00:48","2021-01-26 01:08" }]
(Variable extra timestamps depending on first array i already have)
我需要这个来填充 am4charts.Lineseries 的 chartsData 数组。
有人可以帮我吗?或者有没有更好的选择?
解决方法
这种问题是您遍历数组的元素并根据某些规则对某些内容进行分组。
这是 Array.reduce 的一个很好的用例(虽然你可以用其他方法做同样的事情)
我会做类似这样的功能:
function indexByCoins(coinsArray) {
const coinsProfitByCoin = coinsArray.reduce((accumulator,coinInfo) => {
const { coin,profit,timestamp } = coinInfo
if (!accumulator[coin]) {
accumulator[coin] = []
}
accumulator[coin].push({ profit,timestamp })
return accumulator
},{})
return coinsProfitByCoin
}
它没有按照您的要求完全,而是将每个条目的利润与其时间戳分组。所以你会得到:
{
AION: [
{ profit: '3.10',timestamp: '2021-01-26 00:48:01' },{ profit: '4.00',timestamp: '2021-01-26 01:08:01' }
],BTC: [
{ profit: '77.00',timestamp: '2021-01-26 00:08:04' },{ profit: '78.10',timestamp: '2021-01-26 01:08:04' }
]
}
,
let arr=[{
"coin": "AION","profit": "3.10","timestamp": "2021-01-26 00:48:01"
},{
"coin": "BTC","profit": "77.00","timestamp": "2021-01-26 00:08:04"
},{
"coin": "AION","profit": "4.00","timestamp": "2021-01-26 01:08:01"
},"profit": "78.10","timestamp": "2021-01-26 01:08:04"
}]
let timestampArr=[...new Set(arr.map(item=> item['timestamp']))]
let coinArray=[...new Set(arr.map(item=> item['coin']))]
let AionProfilt=[],btcProfit=[];
arr.map(item=>{
if(item.coin==='BTC')
AionProfilt.push(item.profit)
else
btcProfit.push(item.profit)
})
console.log(coinArray,AionProfilt,btcProfit,timestampArr)
,
您可以使用函数 Array.prototype.reduce
对所需的输出进行分组和构建。
const array = [{ "coin": "AION","timestamp": "2021-01-26 00:48:01"},{ "coin": "BTC","timestamp": "2021-01-26 00:08:04"},{ "coin": "AION","timestamp": "2021-01-26 01:08:01"},"timestamp": "2021-01-26 01:08:04"}],result = array.reduce((a,{coin,timestamp}) => {
a.coins.push(coin);
a.timestamps.push(timestamp);
(a.profits[coin] || (a.profits[coin] = [])).push(profit);
return a;
},{coins: [],profits: {},timestamps: []});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。