如何在 Javascript 中将数组从一种模式转换为另一种模式?
How to convert an array from one schema to another in Javascript?
我有一个 JSON 数组,如下所示:
[{
"day":"all",
"client_first":"3",
"client_second":"2",
"client_third":"3"
},
{
"day":"monday",
"client_first":"2",
"client_second":"2",
"client_third":"2"
}]
我想把上面的改成下面的
[{
label: 'all',
data: [3,2,3]
},
{
label: 'monday',
data: [2,2,2]
}]
提前致谢
给定输入:
const input = [{
"day":"all",
"client_first":"3",
"client_second":"2",
"client_third":"3"
},
{
"day":"monday",
"client_first":"2",
"client_second":"2",
"client_third":"2"
}];
看起来你想做的事情的语义与 Array.map
非常吻合。
对于输入数组中的每个值,将其映射到一个对象,使得 label
由 day
(键重命名)设置,并将 data
的值放入其他条目。
要获取条目(键,值对),我们使用 Object.entries
. We Array.filter
to get those with key !== 'day'
. We want an array of the values, so we map the filtered entries (key,value pairs) to only the values. The input is string, but looks like you want it as numbers, so we convert using Number
函数
const output = input.map(obj => ({
label: obj.day,
data: Object.entries(obj).filter(([key]) => key !== 'day').map(([, val]) => Number(val)),
}));
一行代码:
arr.map(({day,...clients})=>({label:day,data:[Object.values(clients).map(Number)]}))
:
- 遍历数组并使用
Destructuring
from object and clients using rest_parameters
获取 day
let arr = [{
"day":"all",
"client_first":"3",
"client_second":"2",
"client_third":"3"
},
{
"day":"monday",
"client_first":"2",
"client_second":"2",
"client_third":"2"
}];
console.log(arr.map(({day,...clients})=>({label:day,data:[Object.values(clients).map(Number)]})))
我有一个 JSON 数组,如下所示:
[{
"day":"all",
"client_first":"3",
"client_second":"2",
"client_third":"3"
},
{
"day":"monday",
"client_first":"2",
"client_second":"2",
"client_third":"2"
}]
我想把上面的改成下面的
[{
label: 'all',
data: [3,2,3]
},
{
label: 'monday',
data: [2,2,2]
}]
提前致谢
给定输入:
const input = [{
"day":"all",
"client_first":"3",
"client_second":"2",
"client_third":"3"
},
{
"day":"monday",
"client_first":"2",
"client_second":"2",
"client_third":"2"
}];
看起来你想做的事情的语义与 Array.map
非常吻合。
对于输入数组中的每个值,将其映射到一个对象,使得 label
由 day
(键重命名)设置,并将 data
的值放入其他条目。
要获取条目(键,值对),我们使用 Object.entries
. We Array.filter
to get those with key !== 'day'
. We want an array of the values, so we map the filtered entries (key,value pairs) to only the values. The input is string, but looks like you want it as numbers, so we convert using Number
函数
const output = input.map(obj => ({
label: obj.day,
data: Object.entries(obj).filter(([key]) => key !== 'day').map(([, val]) => Number(val)),
}));
一行代码:
arr.map(({day,...clients})=>({label:day,data:[Object.values(clients).map(Number)]}))
:
- 遍历数组并使用
Destructuring
from object and clients usingrest_parameters
获取 day
let arr = [{
"day":"all",
"client_first":"3",
"client_second":"2",
"client_third":"3"
},
{
"day":"monday",
"client_first":"2",
"client_second":"2",
"client_third":"2"
}];
console.log(arr.map(({day,...clients})=>({label:day,data:[Object.values(clients).map(Number)]})))