首页 > 解决方案 > 如何在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
    }
   })

但它给出了错误。请帮助解决这个问题。

标签: javascriptnode.js

解决方案


您可以在以下范围内利用解构语法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%;}


推荐阅读