通过键值映射需要 NodeJS JSON 响应
Posted
技术标签:
【中文标题】通过键值映射需要 NodeJS JSON 响应【英文标题】:NodeJS JSON response required through key value mapping 【发布时间】:2022-01-16 18:58:51 【问题描述】:如果事件不可用,则获取一些事件及其数据,我们必须设置零值。 获取如下数据,
"result" :
"2" :
"buckets" : [
"3" :
"buckets" : [
"key" : "updated",
"doc_count" : 5
,
"key" : "created",
"doc_count" : 3
,
"key" : "deleted",
"doc_count" : 3
]
,
"3" :
"buckets" : [
"key" : "created",
"doc_count" : 1
,
"key" : "deleted",
"doc_count" : 1
]
,
"3" :
"buckets" : [
"key" : "created",
"doc_count" : 46
]
]
期望的响应: "chartData":"dataset":["label":"created","data":[3,1,46,],"label":"updated","data":[5, 0,0],"label":"deleted","data":[3,1,0]]
如何动态设置标签和数据?
【问题讨论】:
请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。 【参考方案1】:您需要先初始化空项,然后重新构建数据并将数据映射到您的预期结构。
const input =
"2" :
"buckets" : [
"3" :
"buckets" : [
"key" : "updated",
"doc_count" : 5
,
"key" : "created",
"doc_count" : 3
,
"key" : "deleted",
"doc_count" : 3
]
,
"3" :
"buckets" : [
"key" : "created",
"doc_count" : 1
,
"key" : "deleted",
"doc_count" : 1
]
,
"3" :
"buckets" : [
"key" : "created",
"doc_count" : 46
]
]
const decoratedInputs = input['2']['buckets']
.map(item =>
const rawItems = item['3']['buckets']
const formattedItems = []
const created = rawItems.find(item => item.key === 'created')
if (!created)
// init created item
formattedItems.push(key: 'created', doc_count: 0)
else
formattedItems.push(created)
const deleted = rawItems.find(item => item.key === 'deleted')
if (!deleted)
// init deleted item
formattedItems.push(key: 'deleted', doc_count: 0)
else
formattedItems.push(deleted)
const updated = rawItems.find(item => item.key === 'updated')
if (!updated)
// init updated item
formattedItems.push(key: 'updated', doc_count: 0)
else
formattedItems.push(updated)
return formattedItems
)
const result =
chartData:
dataset: [
label: 'created',
data: decoratedInputs.map(item =>
const created = item.find(item => item.key === 'created')
return created.doc_count
)
,
label: 'updated',
data: decoratedInputs.map(item =>
const updated = item.find(item => item.key === 'updated')
return updated.doc_count
)
,
label: 'deleted',
data: decoratedInputs.map(item =>
const deleted = item.find(item => item.key === 'deleted')
return deleted.doc_count
)
]
console.log(result)
【讨论】:
以上是关于通过键值映射需要 NodeJS JSON 响应的主要内容,如果未能解决你的问题,请参考以下文章