0

My question is quite similar to this one: Merge keys array and values array into an object in JavaScript

However, I don't seem to find the solution for my example. If I have these two arrays:

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

How do I combine them into an array of objects, such that would be the expected result?

[
  {
    x: 0,
    y: 1,
    z: 2,
  },
  {
    x: 10,
    y: 20,
    z: 30,
  },
]
FMM
  • 1,857
  • 1
  • 15
  • 38

3 Answers3

1

Cycle through the value arrays and create an object for each, then cycle through the values within those arrays and use the keys array as the keys.

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

const output = [];
values.forEach((v, i) => {
  output[i] = {}; // create objects for each of the value arrays
  v.forEach((w, j) => {
    output[i][keys[j]] = w; // use the correct keys with each of the values
  });
});

console.log(output);

As comments have also pointed out, this can be done with Array.reduce:

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

const output = values.map(x => { // for each of the values arrays
  return x.reduce((a, c, i) => { // take its values
    a[keys[i]] = c // map them to an object property one by one
    return a; // put them together in the same object.
  }, {});
});

console.log(output);
LaytonGB
  • 1,384
  • 1
  • 6
  • 20
1

You can use Array.prototype.map() and Array.prototype.reduce() for this:

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

const res = values.map(arr => arr.reduce((acc, curr, index) => {
  acc[keys[index]] = curr

  return acc;
}, {x: null, y: null, z: null}));

console.log(res);

Or you can also do it without reduce() like so:

const res = values.map(arr => ({
  [keys[0]]: arr[0],
  [keys[1]]: arr[1],
  [keys[2]]: arr[2]
}));
zb22
  • 3,126
  • 3
  • 19
  • 34
0

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];


function toObject(keys, values) {
    let final = []
     for (let i = 0; i < values.length; i++){
         let result = {};
         for(let j=0;j<keys.length;j++){
             result[keys[j]] = values[i][j];
            
         }
        final.push(result)
     }
    return final 
    console.log(final)
     
 }
 
 toObject(keys,values )

it will work

Sadi
  • 1
  • 2