如何将一个对象json转换为数组对象json?

时间:2016-05-17 08:46:44

标签: javascript jquery html arrays json

我的对象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"
    }]
}];

解决我问题的任何解决方案?

非常感谢

3 个答案:

答案 0 :(得分: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>');

答案 1 :(得分:2)

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

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

Working example

答案 2 :(得分:0)

希望这会有所帮助

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