如何将json元素分组以进行交换[关闭]
Posted
技术标签:
【中文标题】如何将json元素分组以进行交换[关闭]【英文标题】:How to group json elements for exchange [closed] 【发布时间】:2021-07-29 23:20:56 【问题描述】:我对组 json 元素有一些问题。我想计算实时价格深度,但我需要使用参数小数。
我有这个来自 websocket 的带有 binance api 的 json。
"symbol": "btcusdt",
"depth": [
"price": 38980,
"qty": 1.34
,
"price": 39100,
"qty": 1.34
,
"price": 39200,
"qty": 2.44
,
"price": 39500,
"qty": 7.31
,
"price": 40230,
"qty": 11.34
]
我需要有数量的团体价格。示例:
"symbol": "btcusdt",
"depth": [
"price": 38000,
"qty": 1.34
,
"price": 39000,
"qty": 11.09
,
"price": 40000,
"qty": 11.34
]
我为此使用 websocket。 Json 元素总是刷新。
【问题讨论】:
“组”是什么意思? @Spectric 看起来他正在组合相同数千范围内的所有元素,并将数量相加。 【参考方案1】:将depth
数组缩减为一个对象,其键是向下舍入到 1000 倍数的价格。
const data =
"symbol": "btcusdt",
"depth": [
"price": 38000,
"qty": 1.34
,
"price": 39000,
"qty": 11.09
,
"price": 40000,
"qty": 11.34
]
;
data.depth = Object.values(data.depth.reduce((acc,
price,
qty
) =>
let thousands = price - price % 1000;
if (acc[thousands])
acc[thousands].qty += qty;
else
acc[thousands] =
price: thousands,
qty: qty
;
return acc;
, ));
console.log(data);
【讨论】:
【参考方案2】:您可以创建一个排序器对象。将底价设置为关键,然后进行迭代。
解析你的 json 之后
const myJson =
"symbol": "btcusdt",
"depth": [
"price": 38980,
"qty": 1.34
,
"price": 39100,
"qty": 1.34
,
"price": 39200,
"qty": 2.44
,
"price": 39500,
"qty": 7.31
,
"price": 40230,
"qty": 11.34
]
let foo = , sorted = []
myJson.depth.forEach(entry =>
let price = Math.floor(entry.price / 1000) * 1000
if (foo[price])
foo[price].qty += entry.qty
else
entry.price = price
foo[price] = entry
)
sorted =
symbol: myJson.symbol,
depth: Object.values(foo)
console.log(sorted)
至少我发现这样做的最有效方式..
【讨论】:
以上是关于如何将json元素分组以进行交换[关闭]的主要内容,如果未能解决你的问题,请参考以下文章