Priyanka
Priyanka

Reputation: 117

How to form a dynamic json array in nodejs?

I have a set of values in my db. After reading that, my output will be like below.

FetchValues = 
  [{
   "Key": "123"
    "Value":"aa"
     "Type":"A"},
    {},
    {}
   ]

I need to form a dynamic json array like below after fetching the values from DB.

 {
  "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
    }
   })

But it gives error. Kindly help on this.

Upvotes: 1

Views: 305

Answers (2)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

You may leverage destructuring syntax within 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%;}

Or (if your actual intention was to output an object, rather than array):

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%;}

Upvotes: 4

NullDev
NullDev

Reputation: 7303

@Yevgen Gorbunkov's answer is way better, but here's an approach using forEach:

const src = [{Key:"123",Value:"aa",Type:"A"},{Key:"124",Value:"bb",Type:"B"}];

let res = {};
src.forEach(element => res[element.Type] = { [element.Key]: element.Value });

Upvotes: 1

Related Questions