我有一个这样的数组:
[{
"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"
},
{
"coin": "BTC",
"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, ZIL, ARK, 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数组。
有人能帮帮我吗?还有没有更好的选择呢?
发布于 2021-01-27 03:50:02
这是一种问题,你迭代数组的元素,并根据一些规则对一些东西进行分组。
这是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' }
]
}发布于 2021-01-27 03:54:49
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"
},
{
"coin": "BTC",
"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)发布于 2021-01-27 04:32:24
您可以使用函数Array.prototype.reduce对所需的输出进行分组和构建。
const array = [{ "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"},{ "coin": "BTC", "profit": "78.10", "timestamp": "2021-01-26 01:08:04"}],
result = array.reduce((a, {coin, profit, 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; }
https://stackoverflow.com/questions/65907973
复制相似问题