Convert JSON object containing objects into an array of objects

怎甘沉沦 提交于 2019-12-13 23:18:07

问题


My data is currently stored in this format, stored in a JSON file:

{
    "name": {
        "0": ______,
        "1": ______,
        "2": ______
    },
    "xcoord": {
        "0": ______,
        "1": ______,
        "2": ______
    },
    "ycoord": {
        "0": ______,
        "1": ______,
        "2": ______
    }
}

And I need to convert it into this format, as an array of objects:

[
    {
        "id": 0,
        "name": _____,  
        "xcoord": _____,
        "ycoord": _____
    },
    {
        "id": 1,
        "name": _____,
        "xcoord": _____,
        "ycoord": _____
    },
    {
        "id": 2,
        "name": _____,
        "xcoord": _____,
        "ycoord": _____
    }
]

As you can see, I also need to take the number keys in my first data format and make them the "id" values in my second data format. (Since the position of the object in the array and the id number match up, maybe that would be another way to create the "id" key?) I would then store my second data format into a local variable to use in my JS code.

Any ideas on how I can do this? I'm not very good with restructuring this kind of data.


回答1:


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];


来源:https://stackoverflow.com/questions/38695977/convert-json-object-containing-objects-into-an-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!