我有这样的嵌套数组
array = [[1, 698],[32, 798],[69, 830],[95, 500]]
Run Code Online (Sandbox Code Playgroud)
我想要一个以这种格式返回结果的函数
[
{
id: 1,
score: 698
},
{
id: 32,
score: 798
},
{
id: 69,
score:830
},
..... the rest of the array
]
Run Code Online (Sandbox Code Playgroud)
我确实使用了for循环,但没有成功,我不知道如何处理这种情况.
for(var i = 0; i <= array.lenght ; i++){
var obj={}
var res = []
res.push(array[i])
}
Run Code Online (Sandbox Code Playgroud)
Abd*_*rif 10
您可以利用ES6语法的强大功能:
var array = [
[1, 698],
[32, 798],
[69, 830],
[95, 500],
];
var res = array.map(([id, score]) => ({id, score}));
console.log(res);Run Code Online (Sandbox Code Playgroud)
您可以将Array.prototype.map()与解构赋值一起使用:
const array = [[1, 698],[32, 798],[69, 830],[95, 500]];
const result = array.map(([id, score]) => ({id, score}));
console.log(result);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |