将Json数组转换为普通json

时间:2016-12-01 13:08:36

标签: javascript json

这是我的回答:

{
    "item": [{
        "key": "name",
        "value": "john"
    }, {
        "key": "number",
        "value": "1234"
    }, {
        "key": "price",
        "value": [{
            "item": [{
                "item": [{
                    "key": "quantity",
                    "value": "20"
                }, {
                    "key": "price",
                    "value": "200"
                }]
            }]
        }]
    }]
}

需要转换为:

{
    "name": "john",
    "number": "1234",
    "price": {
        "quantity": "20",
        "price": "200"
    }
}

2 个答案:

答案 0 :(得分:0)



Trying to get property of non-object




答案 1 :(得分:0)

您可以对item使用嵌套方法并迭代所有数组并为每个数组调用函数iter

此解决方案使用Array#forEach中的thisArg作为结果的下一个更深层次的对象。

var data = { "item": [{ "key": "name", "value": "john" }, { "key": "number", "value": "1234" }, { "key": "price", "value": [{ "item": [{ "item": [{ "key": "quantity", "value": "20" }, { "key": "price", "value": "200" }] }] }] }] },
    result = {};

[data].forEach(function iter(a) {
    if ('item' in a) {
        a.item.forEach(iter, this);
        return;
    }
    if (Array.isArray(a.value)) {
        this[a.key] = {};
        a.value.forEach(iter, this[a.key]);
        return;
    }
    this[a.key] = a.value;
}, result);

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