将包含对象的JSON对象转换为对象数组 [英] Convert JSON object containing objects into an array of objects

查看:363
本文介绍了将包含对象的JSON对象转换为对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据当前以这种格式存储,并存储在JSON文件中:

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": _____
    }
]

如您所见,我还需要使用第一种数据格式的数字键,并使其以第二种数据格式的"id"值. (由于对象在数组中的位置和id编号匹配,也许这是创建"id"键的另一种方法?)然后,我将第二种数据格式存储到本地变量中,以便在我的JS代码中使用

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.

推荐答案

例如,可以使用两个交叉的.forEach()来完成此操作:

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

注意:

此行...

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

这篇关于将包含对象的JSON对象转换为对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆