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!

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.