[英]Convert a list of lists into a list of dictionaries using Javascript
是否有使用 javascript 的内置方式将列表列表转换为字典列表?
前
[
[
"x",
"y",
"z",
"total_count",
"total_wins"
],
[
25.18,
24.0,
27520.0,
16,
6,
],
[
25.899,
24.0,
27509.0,
336,
8
],
[
26.353,
26.0,
27256.0,
240.0,
15
],
[
119.0,
5.0,
6.0,
72,
0
]
]
后
[
{
"x": 25.18,
"y": 24.0,
"z": 27520.0,
"total_count": 16,
"total_wins": 6,
},
{
"x": 25.899,
"y": 24.0,
"z": 27509.0,
"total_count": 336,
"total_wins": 8
},
{
"x": 26.353,
"y": 26.0,
"z": 27256.0,
"total_count": 240.0,
"total_wins": 15
},
{
"x": 119.0,
"y": 5.0,
"z": 6.0,
"total_count": 72,
"total_wins": 0
}
]
也许没有内置,但有一种方法
const input = [["x", "y", "z", "total_count", "total_wins"], [25.18, 24.0, 27520.0, 16, 6,], [25.899, 24.0, 27509.0, 336, 8], [26.353, 26.0, 27256.0, 240.0, 15], [119.0, 5.0, 6.0, 72, 0]]; const keys = input.shift(); console.log(input.map(values => Object.fromEntries(keys.map((key, idx) => [ key, values[idx] ]))));
您可以使用rest operator, map and Object.fromEntries
let data = [["x", "y", "z", "total_count", "total_wins"], [25.18, 24.0, 27520.0, 16, 6,], [25.899, 24.0, 27509.0, 336, 8], [26.353, 26.0, 27256.0, 240.0, 15], [119.0, 5.0, 6.0, 72, 0]]; let [keys, ...rest] = data let final = rest.map(inp => Object.fromEntries(inp.map((value, index) => [keys[index], value]))) console.log(final)
如果您在不支持 Object.fromEntries 的环境中工作,那么您可以使用 reduce
let data = [["x", "y", "z", "total_count", "total_wins"], [25.18, 24.0, 27520.0, 16, 6,], [25.899, 24.0, 27509.0, 336, 8], [26.353, 26.0, 27256.0, 240.0, 15], [119.0, 5.0, 6.0, 72, 0]]; let [keys, ...rest] = data let buildObject = (valueArr) => { return valueArr.reduce((op, inp, index) => { op[keys[index]] = inp return op }, {}) } let final = rest.map(inp => buildObject(inp, keys)) console.log(final)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.