Airynd Airynd - 10 months ago 67
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}]},

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},

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;


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 :).


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: