如何将 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>");
希望我问的是对的。
我有一个数组 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>");