2016-04-13 4 views
-1

Ich hoffe ich frage das richtig.Wie konvertiert man ein JSON-Array in ein Schlüsselwert-Array?

Ich habe ein Array notes in dem jedes Element eine JSON-Linie ist. So zum Beispiel:

//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" 
} 

Was ich will, ist die vorherige Array, so etwas zu konvertieren, so kann ich es verwenden, um ein linewithfocus Diagramm mit nvd3 plotten:

//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"}] 

Wie kann ich es tun ? Ich danke dir sehr.

Antwort

2

Sie können auf diese Weise in den folgenden tun

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

Vielen Dank verwenden können! Die Lösung war viel einfacher als das, was ich dachte. –

1

Sie 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>");