Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  127] [ 5]  / answers: 1 / hits: 5708  / 5 Years ago, fri, february 22, 2019, 12:00:00

I get this JSON from my server. But to work with this JSON i need to Add Square Brackets to the MH Object. How can i do that. I tried .map but i dont get it to work for me. Is there any better solution. Or is .mapto use there. If yes can you show me a hint how to do that. Or is there a better solution?



{
PAD: [
{
PADPS286: Dampf,
PADPS124: Hans,
PADPS60: 2018-05-01,
PADPS143: 1,
MH: {
MHVSS1: [
{}
],
MHDIRW214: 2017,
MHDIRW215: 2018,
birthdate: 2018-05-01,
MHDIRW129 : 0
}
},
{
PADPS286: Snow,
PADPS124: Jon,
PADPS60: 2077-05-01,
PADPS143: ,
MH: {
MHVSS1: [
{}
],
MHDIRW214: 4,
MHDIRW215: 4,
birthdate: 2077-05-01,
MHDIRW129 : 0
}
}
]
}


I need this JSON with sqare Brackets arround teh MH Object



{
PAD: [
{
PADPS286: Dampf,
PADPS124: Hans,
PADPS60: 2018-05-01,
PADPS143: 1,
MH: [{
MHVSS1: [
{}
],
MHDIRW214: 2017,
MHDIRW215: 2018,
birthdate: 2018-05-01,
MHDIRW129 : 0
}]
},
{
PADPS286: Snow,
PADPS124: Jon,
PADPS60: 2077-05-01,
PADPS143: ,
MH: [{
MHVSS1: [
{}
],
MHDIRW214: 4,
MHDIRW215: 4,
birthdate: 2077-05-01,
MHDIRW129 : 0
}
]}
]
}

More From » json

 Answers
0

It's not really adding square brackets, it's wrapping the MH object in an array.



Anyway, here's a .map statement that will do it for you (without mutating the original data, hence the Object.assign shenanigans):



data.PAD = data.PAD.map((padObj) => Object.assign({}, padObj, {MH: [padObj.MH]}));


Basically, for each entry in the PAD array, we're merging three objects there:




  • a fresh empty object {}

  • the original padObj entry

  • a small object that only has the MH element from the original padObj wrapped in an array.



The output is as expected:



{
PAD: [
{
PADPS286: Dampf,
PADPS124: Hans,
PADPS60: 2018-05-01,
PADPS143: 1,
MH: [
{
MHVSS1: [{}],
MHDIRW214: 2017,
MHDIRW215: 2018,
birthdate: 2018-05-01,
MHDIRW129 : 0
}
]
},
{
PADPS286: Snow,
PADPS124: Jon,
PADPS60: 2077-05-01,
PADPS143: ,
MH: [
{
MHVSS1: [{}],
MHDIRW214: 4,
MHDIRW215: 4,
birthdate: 2077-05-01,
MHDIRW129 : 0
}
]
}
]
}

[#8787] Thursday, February 21, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grayson

Total Points: 36
Total Questions: 113
Total Answers: 95

Location: Tonga
Member since Fri, Aug 21, 2020
4 Years ago
;