使用underscrore.js或其他东西进行Javascript对象转换

时间:2016-10-30 14:25:43

标签: javascript object underscore.js transform

我有一个如下的对象:

var obj1 = {

    "Prop1": {
        "Prop2": {
            "Prop2.1": "value1",
            "Prop2.2": "value2"
        },
        "Prop3": {
            "Prop3.1": "value3",
            "Prop3.2": "value4"
        },
        "Prop4": {
            "Prop4.1": "value5",
            "Prop4.2": "value6",
            "Prop4.3": "value7"
        }
    }
};

但我想将此对象转换为下面的对象:

var obj1 = {

    "data": [
    {
            "id": "Prop1",
            "data": [
                {
                    "id": "Prop2",
                    "data": [
                        {"id": "Prop2.1","value": "value1"},
                        {"id": "Prop2.2","value": "value2"}
                    ]
                },
                {
                    "id": "Prop3",
                    "data": [
                        {"id": "Prop3.1","value": "value3"},
                        {"id": "Prop3.2","value": "value4"}
                    ]
                },
                {
                    "id": "Prop4",
                    "data": [
                        {"id": "Prop4.1","value": "value5"},
                        {"id": "Prop4.2","value": "value6"},
                        {"id": "Prop4.3","value": "value7"}
                    ]
                },
            ]
        },
    ]
};

如您所见,对象结构将完全不同。 我可以使用underscore.js或其他方法轻松地进行此更改吗?

1 个答案:

答案 0 :(得分:0)

您可以使用迭代递归方法来构建新对象。

function convert(object) {
    return Object.keys(object).map(function (k) {
        var o = { id: k };
        if (object[k] !== null && typeof object[k] === 'object') {
            o.data = convert(object[k]);
        } else {
            o.value = object[k];
        }
        return o;
    });
}

var source = { Prop1: { Prop2: { "Prop2.1": "value1", "Prop2.2": "value2" }, Prop3: { "Prop3.1": "value3", "Prop3.2": "value4" }, Prop4: { "Prop4.1": "value5", "Prop4.2": "value6", "Prop4.3": "value7" } } },
    target = { data: convert(source) };

console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }