【问题标题】:How to convert one object json to array object json?如何将一个对象 json 转换为数组对象 json?
【发布时间】:2016-05-17 08:46:44
【问题描述】:

我的对象 json 是这样的:

var a = [{
    "attributes": {
        "Code": "SGL",
        "Total": "811400"
    },
    "DayPrice": {
        "Date": "2016-07-22",
        "Rate": "811400"
    }
}];

我想将 DayPrice 更改为这样的数组:

var a = [{
    "attributes": {
        "Code": "SGL",
        "Total": "811400"
    },
    "DayPrice": [{
        "Date": "2016-07-22",
        "Rate": "811400"
    }]
}];

有什么办法可以解决我的问题吗?

非常感谢

【问题讨论】:

    标签: javascript jquery html arrays json


    【解决方案1】:

    您需要遍历对象数组并将每个对象的 DayPrice 属性包装在一个数组中,如下所示:

    for (var i = 0; i < a.length; i++) {
        a[i].DayPrice = [a[i].DayPrice];
    }
    

    Working example

    【讨论】:

    【解决方案2】:

    将具有该属性的数组分配给该属性。

    a[1].DayPrice = [a[1].DayPrice];
    

    或者使用循环:

    var a = [{ "attributes": { "Code": "SGL", "Total": "811400" }, "DayPrice": { "Date": "2016-07-22", "Rate": "811400" } }];
    
    a.forEach(function (a) {
        if ('DayPrice' in a) {
            a.DayPrice = [a.DayPrice];
        }
    });
    
    document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>');

    【讨论】:

    【解决方案3】:

    希望这会有所帮助

    var a = [{
                "attributes": {
                    "Code": "SGL",
                    "Total": "811400"
                },
                "DayPrice": {
                    "Date": "2016-07-22",
                    "Rate": "811400"
                }
            }];
    
    var _getDayPrice = a[0].DayPrice;
    
    var _dayPriceArray = [];
    _dayPriceArray.push({
      "Date":_getDayPrice.Date,
      "Rate":_getDayPrice.Rate
    })
    a[0].DayPrice=_dayPriceArray;
    console.log(a);
    

    查看jsFiddle

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2012-07-21
    • 2020-10-02
    相关资源
    最近更新 更多