10

I have arrays of arrays which contains something like this:

var values = [[1, 2, 3], [3, 2, 1]]

I've tried .map() and Object.assign but I dont know how to implement it. I want this as an output:

values = [
    {'up': 1, 'middle': 2, 'down': 3},
    {'up': 3, 'middle': 2, 'down': 1}
]

What should I use? This is what Im came up so far:

const object1 = [[1,2,3],[3,2,1]],
  object = []

object1.forEach(function(array) {
   object.map(value => ({'up': array[0], 'mid': array[1], 'down': array[2]}))
 });

console.log(object)
1
  • what is the expected output. always put 1st, 2nd or 3rd index or sort it first then arrange? Commented Oct 26, 2018 at 6:14

2 Answers 2

13

Not very different from what others already did, but a little more elegant:

let arr = [[1, 2, 3], [3, 2, 1]];

let result = arr.map(([up, middle, down]) => ({up, middle, down}));
console.log(result);

1
  • 1
    I'd say not only a little more elegant but so much simpler it's clearly the one correct way of doing this.
    – JollyJoker
    Commented Oct 26, 2018 at 12:40
3

you can simply use Array.map(), there is no need of forEach()

let arr =[[1, 2, 3], [3, 2, 1]];

let result = arr.map((e)=>({"up" : e[0], "mid"  : e[1], "down" : e[2]}));
console.log(result);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.