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.
asked Oct 20, 2020 at 17:19
Priyanka
1171 gold badge5 silver badges19 bronze badges
-
1Please include the error you are receiving.Philip Raath– Philip Raath2020年10月20日 17:22:29 +00:00Commented Oct 20, 2020 at 17:22
-
It is syntax error while trying to form a json and push in to an arrayPriyanka– Priyanka2020年10月20日 17:23:39 +00:00Commented Oct 20, 2020 at 17:23
-
By JSON, do you mean object?AlexH– AlexH2020年10月20日 17:23:51 +00:00Commented Oct 20, 2020 at 17:23
2 Answers 2
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%;}
answered Oct 20, 2020 at 17:25
Yevhen Horbunkov
15.6k3 gold badges27 silver badges46 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
@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 });
answered Oct 20, 2020 at 17:30
NullDev
7,3784 gold badges37 silver badges59 bronze badges
Comments
lang-js