arkahn jihu
arkahn jihu

Reputation: 109

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])
}

Upvotes: 4

Views: 213

Answers (6)

Scott Sauyet
Scott Sauyet

Reputation: 50797

The answers from a number of people suggesting .map(([id, score]) => ({id, score})) are great. But if you have to do things like this often, you might want to write a reusable function to make this more declarative. For that, something like this might work:

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'])))

Note that you could also extend this to

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

and just call

zipAllObjects(['id', 'score'])(array)

Upvotes: 2

Abslen Char
Abslen Char

Reputation: 3135

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);

Upvotes: 10

Jason
Jason

Reputation: 15931

first you need a function that takes a 2 element array and returns an object

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

you will want to add error handling, but thats the basic idea.

Next you want to iterate over the array of arrays transforming each value (2 element array) into an object. Thats called mapping over values, and js supports it natively

const arrayOfObjects =  array.map(objBuilder)

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

Upvotes: 2

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

You can use Array.prototype.map() with destructuring assignment:

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

console.log(result);

Upvotes: 6

MyTwoCents
MyTwoCents

Reputation: 7624

var sampleArray = [[1, 698],[32, 798],[69, 830],[95, 500]];

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


// Final Result
console.log(finalJson);

Upvotes: 3

Faly
Faly

Reputation: 13356

Use array.prototype.map, destructuring and shorthand object litteral:

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

Upvotes: 4

Related Questions