[Solved] Convert JSON object containing objects into an array of objects


This can be done for instance with two imbricated .forEach():

var obj = {
    "name": {
        0: 'name0',
        1: 'name1',
        2: 'name2'
    },
    "xcoord": {
        0: 'xcoord0',
        1: 'xcoord1',
        2: 'xcoord2'
    },
    "ycoord": {
        0: 'ycoord0',
        1: 'ycoord1',
        2: 'ycoord2'
    }
};

var res = [];

Object.keys(obj).forEach(k => {
  Object.keys(obj[k]).forEach(v => {
    (res[v] = (res[v] || { id: v }))[k] = obj[k][v];
  });
});

console.log(res);

Note:

This line …

(res[v] = (res[v] || { id: v }))[k] = obj[k][v]

… is a short way to do:

if(!res[v]) {
  // if this record doesn't exist yet,
  // create it with its implied 'id' property
  res[v] = { id: v };
}
// add property 'k' to this record
res[v][k] = obj[k][v];

solved Convert JSON object containing objects into an array of objects