1

I have two arrays,

keys: ["idClient", "idProject","price"]

and

values: [[1,2,123],[1,3, 45],[2,3,10]]

Is it posible to transform these two arrays into one object like:

[
  {
    "idClient": 1,
    "idProject": 2,
    "price": 123
  },
  {
    "idClient": 1,
    "idProject": 3,
    "price": 45
  },
  {
    "idClient": 2,
    "idProject": 3,
    "price": 10
  }
]

I used something like this :

keys.reduce((obj, key, index) => ({ ...obj, [key]: values[index] }), {});

But it groups values per key, not in the way I want..

idClient: (3) [1, 2, 123]

Any help would be appreciated. Thanks in advance!

Aw3same
  • 930
  • 4
  • 13
  • 38

1 Answers1

3

Use Array.prototype.reduce function inside Array.prototype.map function of values and it will work.

const keys = ["idClient", "idProject","price"];
const values = [[1,2,123],[1,3, 45],[2,3,10]];

const output = values.map((item) => item.reduce((acc, curV, curI) => {
  acc[keys[curI]] = curV;
  return acc;
}, {}));
console.log(output);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39