Airynd Airynd - 6 months ago 27
JSON Question

Javascript Array Manipulation - complex JSON response

example an object array is sent by the server -

var x = [{a:1,b:2,c:3,d:[{f:6,g:7}],e:[{h:8}]},
{a:1,b:2,c:3,d:[{f:6,g:7}],e:[{h:8}]},
{a:1,b:2,c:3,d:[{f:6,g:7}],e:[{h:8}]}];


how do I alter it so it looks like this -

var y = [{a:1,b:2,c:3,h:8},{f:6,g:7,h:8},
{a:1,b:2,c:3,h:8},{f:6,g:7,h:8},
{a:1,b:2,c:3,h:8},{f:6,g:7,h:8}];


I've tried this ugly code just now -

function arrange(arr){
var temp1 = [];
var temp2 = [];
var output = [];

for(var i = 0;i < arr.length;i++){
temp1 = arr[i].d;
temp2 = arr[i].e;
temp1.push(temp2[0].h);

output.push(arr[i].a,arr[i].b,arr[i].c,temp2[0].h);
output.push(temp1);

return output;
}
}


The output is wrong and only gives me the values, I need the key/value pair.

I want to send the correct response to the View. I'm working in a different kinda job at the moment and studying programming is what I do on the side. Right now, I'm stuck. Please forgive the horrible code :).

Answer

Javascript explicitly provides for destructured expressions: a very concise way to extract the the data into objects that you desired.

let result = x.reduce((elts, {a, b, c, d: [{f, g}], e: [{h}]}) => {
  return elts.concat({a, b, c, h}, {f, g, h})
}, [])

If you console.log the variable result, you'll find it gives your desired values in y:

[{"a":1,"b":2,"c":3,"h":8},{"f":6,"g":7,"h":8},{"a":1,"b":2,"c":3,"h":8},{"f":6,"g":7,"h":8},{"a":1,"b":2,"c":3,"h":8},{"f":6,"g":7,"h":8}]
Comments