javascript - 如何在nodejs中形成一个动态的json数组?
问题描述
我的数据库中有一组值。读完之后,我的输出将如下所示。
FetchValues =
[{
"Key": "123"
"Value":"aa"
"Type":"A"},
{},
{}
]
从数据库中获取值后,我需要形成一个如下所示的动态 json 数组。
{
"A":{
"123" : "aa"
},
{
"B": {
"124" : "bb"
}
}
var Json = {}
for(k=0;k<fetchValues.length;k++)
{
Json.push({ fetchValues[k].Type
: {
fetchValues[k].Key : fetchValues[k].Value
}
})
但它给出了错误。请帮助解决这个问题。
解决方案
您可以在以下范围内利用解构语法Array.prototype.map()
:
const src = [{Key:"123",Value:"aa",Type:"A"},{Key:"124",Value:"bb",Type:"B"}],
result = src.map(({Key, Value, Type}) => ({[Type]:{[Key]:Value}}))
console.log(result)
.as-console-wrapper{min-height:100%;}
或者(如果您的实际意图是输出一个对象,而不是数组):
const src = [{Key:"123",Value:"aa",Type:"A"},{Key:"124",Value:"bb",Type:"B"}],
result = src.reduce((acc, {Key, Value, Type}) =>
(acc[Type] = {[Key]:Value}, acc), {})
console.log(result)
.as-console-wrapper{min-height:100%;}
推荐阅读
- java - 当检测到某种声音(例如拍手)时触发 android 应用
- python - Python InDesign 脚本:如何运行预检检查?
- java - 数组 = 复杂数据类型 = 类?
- spring-boot - 使用 spring 云流 kafka 绑定消费者和启用 DLQ 覆盖重试尝试
- css - 翻译经典的 css 样式表以响应样式组件使用 + 选择器
- loops - Ansible 循环通过 json 输出并添加索引
- typescript - Mikro ORM TypeScript:在 persist().flush() 上回滚数据库更改
- javascript - 无法将数据保存到 React 中的本地存储
- azure-logic-apps - 在 Azure 逻辑应用参数中设置和解包对象数组
- elasticsearch - 用于 IPRange 的 Elasticsearch SearchQuery 在 kibana 中工作,但在 java 中没有返回命中