Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert arrays of arrays to object with key

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)
like image 552
Cheryl Blossom Avatar asked Oct 26 '18 06:10

Cheryl Blossom


People also ask

How do I turn an array into an array of objects?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result.

Can object keys be arrays?

Description. Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.

How do you push an object with key and value into an array?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.

How do I find the key of an array of objects?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.


2 Answers

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);
like image 197
Amit Avatar answered Sep 21 '22 13:09

Amit


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);
like image 24
amrender singh Avatar answered Sep 20 '22 13:09

amrender singh