简体   繁体   中英

How to convert a JSON array to a key value array?

I hope I am asking this correctly.

I have an array notes in which each element is a JSON line. So for example:

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

What I want is to convert the previous array to something like this, so I can use it to plot a linewithfocus chart with nvd3:

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

How can I do it? Thank you so much.

You can do this in following way

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

You can use 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>"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM