簡體   English   中英

如何將一個對象json轉換為數組對象json?

[英]How to convert one object json to array object 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"
    }]
}];

有什么解決方案可以解決我的問題嗎?

非常感謝你

將具有屬性的數組分配給該屬性。

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>'); 

您將需要遍歷對象數組並將每個對象的DayPrice屬性包裝在數組中,如下所示:

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

工作實例

希望這會有所幫助

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM