簡體   English   中英

如何將JSON數組轉換為鍵值數組?

[英]How to convert a JSON array to a key value array?

我希望我正確地問了這個。

我有一個數組notes ,其中每個元素都是JSON行。 因此,例如:

//notes[0] contains this line
{
"id":"23",
"valuee":"129",
"datee":"2016-04-05T15:20:08.218+0100"
}

//notes[1] contains this line:
{
"id":"24",
"valuee":"131",
"datee":"2016-04-05T15:20:10.272+0100"
}

我想要的是將先前的數組轉換為類似的格式,因此我可以使用它來繪制帶有nvd3的linewithfocus圖表:

  //notes[0] contains this line
{
key:"23",
values:[{x:"129",y:"2016-04-05T15:20:08.218+0100"}]

//notes[1] contains this line:
{
key:"24",
values:[{x:"131",y:"2016-04-05T15:20:10.272+0100"}]

我該怎么做? 非常感謝。

您可以按照以下方式進行操作

notes.map((note) => {
    return {
        key: note.id,
        values: [{
            x: note.valuee,
            y: note.datee
        }]
    } 
})

您可以使用Array.map

 var data = [{ "id": "23", "valuee": "129", "datee": "2016-04-05T15:20:08.218+0100" }, { "id": "24", "valuee": "131", "datee": "2016-04-05T15:20:10.272+0100" }] var result = data.map(function(o) { return { key: o.id, values: { x: o.valuee, y: o.datee } } }); document.write("<pre>" + JSON.stringify(result,0,4) + "</pre>"); 

暫無
暫無

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

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