在javascript中创建具有自定义结构的对象

时间:2013-10-31 09:37:53

标签: javascript

我需要创建一个具有这种确切结构的数组对象:

{"item1": {
    0 :  {
        color:"description1",
        width:"description2",
        height:"description3"
    }
    1 :  {
        color:"description1",
        width:"description2",
        height:"description3"
    }
    //and so on
},
"item2": {
    0 :  {
        color:"description1",
        width:"description2",
        height:"description3"
    }
    //and so on
}
//and so on
}

Estatically工作正常。现在,我想让它成为恐怖的。因此,主要问题是......如何在构建对象的同时循环数据? 这是我工作的传入对象的一个​​示例:

[
{
    "uid": 1,
    "legendname": "item1",
    "rows": [
        {
            "uid": 0,
            "color": "482400",
            "width": "482400",
            "height": "25"
        },
        {
            "uid": 1,
            "color": "587898",
            "width": "789658",
            "height": "30"
        }
    ]
}
{
    "uid": 2,
    "legendname": "item2",
    "rows": [
        {
            "uid": 0,
            "color": "482400",
            "width": "482400",
            "height": "25"
        }
    ]
}
]

1 个答案:

答案 0 :(得分:0)

如何在构建对象的同时循环数据?

不清楚。但是如果你想根据传入的结构创建一个新的结构,你可以使用它:

// ar = your incoming object
// b_obj = your result

var b_obj = {}
for (var i = 0; i < ar.length; i++)
{
    item = ar[i];
    b_item = {};
    for (var i_row = 0; i_row < item.rows.length; i_row++)
    {
        var row = {};
        row.color = item.rows[i_row].color;
        row.width = item.rows[i_row].width;
        row.height = item.rows[i_row].height;
        b_item[i_row] = row;
    }
    b_obj[item.legendname] = b_item;
}