From a nested array to an object array

I have a nested array like this

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

I want to have a function that returns a result in this format

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

I used the for loop, but did not succeed, and I have no idea how to do this.

for(var i = 0; i <= array.lenght ; i++){
    var obj={}
    var res = []
    res.push(array[i])
}
+4
source share
6 answers

You can take advantage 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);
Run codeHide result
+10
source

You can use Array.prototype.map () with a destructive purpose :

const array = [[1, 698],[32, 798],[69, 830],[95, 500]];
const result = array.map(([id, score]) => ({id, score}));

console.log(result);
Run codeHide result
+6
source

array.prototype.map, destructuring shorthand object litteral:

var array = [[1, 698],[32, 798],[69, 830],[95, 500]];
var result = array.map(([id, score]) => ({id, score}));
console.log(result);
Hide result
+4
var sampleArray = [[1, 698],[32, 798],[69, 830],[95, 500]];

var finalJson = sampleArray.map(([id, score]) => ({id, score}));


// Final Result
console.log(finalJson);
+3

, 2-

const objBuilder = arr => return { id: arr[0], score: arr[1] }

, .

, (2 ) . , , js

const arrayOfObjects =  array.map(objBuilder)

more details about the map function here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

+2
source

The answers from the number of people offering .map(([id, score]) => ({id, score}))are great. But if you have to do such things so often, you can write a reuse function to make it more declarative. Something like this might work for this:

const zipObject = names => values => names.reduce(
  (obj, name, idx) => (obj[name] = values[idx], obj), {}
)

const array = [[1, 698], [32, 798], [69, 830], [95, 500]]
console.log(array.map(zipObject(['id', 'score'])))
Run codeHide result

Please note that you can also expand it to

zipAllObjects = names => listsOfValues => listsOfValues.map(zipObject(names))

and just call

zipAllObjects(['id', 'score'])(array)
+2
source

Source: https://habr.com/ru/post/1695422/


All Articles