[英]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.从数据库获取值后,我需要形成一个如下所示的动态 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
}
})
But it gives error.但它给出了错误。 Kindly help on this.
请对此提供帮助。
You may leverage destructuring syntax within Array.prototype.map()
:您可以在
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%;}
@Yevgen Gorbunkov 's answer is way better, but here's an approach using forEach
: @Yevgen Gorbunkov的答案要好得多,但这里有一种使用
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 });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.