1

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.

3
  • 1
    Please include the error you are receiving. Commented Oct 20, 2020 at 17:22
  • It is syntax error while trying to form a json and push in to an array Commented Oct 20, 2020 at 17:23
  • By JSON, do you mean object? Commented Oct 20, 2020 at 17:23

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

@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 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.