鉴于此JavaScript对象:

[
{
    "label": "NewNetworkServiceProvider",
    "value": "NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
},
{
    "label": "PurchaseOrderNumber",
    "value": "PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
},
{
    "label": "RawRecordType",
    "value": "RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5b1ad"
}
]


我想将其修改为这样。

{
    "Header": {
        "NewNetworkServiceProvider": "NewNetworkServiceProvidera9ae97fe-e59a-4678-91ea-5a03c7d0f5cc",
        "PurchaseOrderNumber": "PurchaseOrderNumberdf932a47-1476-4a78-a9d0-de538ed8306b",
        "RawRecordType": "RawRecordType12e9d37c-f8dd-4251-bc55-7c83732b5629"
    }
}


到目前为止,我的代码看起来像这样,但是我无法在最终结果中使用动态标签。基本上,我想在新输出中动态替换“标签”和“值”。

var lscRespDetail = {};
lscRespDetail.data = {};
lscRespDetail.data.results = [];


for (var i = 0; i <= lscheader.data.results.length; i++) {
    if (lscheader.data.results[i] != undefined) {
        var sLabel = lscheader.data.results[i].label;
        var sValue = lscheader.data.results[i].value;

        var obj = {
            Header: {
                sLabel: lscheader.data.results[i].label, sValue: lscheader.data.results[i].value
            }
        };

        obj.sLabel = sLabel;
        obj.sValue = sValue;


        lscResp.data.results.push(obj);

    }

}

最佳答案

您可以对数组使用简单的迭代

演示:Fiddle
Array.forEach()
编写代码

var obj = {
    header: {}
};
lscheader.data.results.forEach(function (item) {
    obj.header[item.label] = item.value;
});
lscResp.data.results.push(obj);

由于需要从变量值获取对象键,因此需要使用bracket notation

关于javascript - 根据JSON结果创建JSON结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30091727/

10-15 05:44