Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From nested array to array of object

I have a nested array like this

array = [[1, 698],[32, 798],[69, 830],[95, 500]]

I want to have a function that return the result in this format

[
    {
        id: 1,
        score: 698
    },
    {
        id: 32,
        score: 798
    },
    {
        id: 69,
        score:830
    },
  ..... the rest of the array
]

I did use a for loop but with no success, and I have no idea on how to aproach the situation.

for(var i = 0; i <= array.lenght ; i++){
    var obj={}
    var res = []
    res.push(array[i])
}
like image 746
arkahn jihu Avatar asked Nov 28 '22 16:11

arkahn jihu


1 Answers

You can take the advantage of the power of the ES6 syntax:

var array = [
          [1, 698],
          [32, 798],
          [69, 830],
          [95, 500],
        ];
var res = array.map(([id, score]) => ({id, score}));
console.log(res);
like image 94
Abslen Char Avatar answered Dec 09 '22 23:12

Abslen Char