Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Constructing an array of object with two arrays

Is there a nice way of transforming a flat javascript array into an array of objects?

An example would be to transform this array.

I’m stuck in trying to merge the two arrays and create an object with the values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const dataSet = [
  {
    last_updated: 1662040601,
    x: [
      1660953600, 1661040000, 1661126400, 1661212800, 1661299200, 1661385600,
      1661472000, 1661558400, 1661644800, 1661731200, 1661817600, 1661904000,
    ],
    y: [
      0.07, 0.062, 0.06, 0.0725, 0.075, 0.089, 0.0799, 0.1167, 0.089, 0.08,
      0.077, 0.0639,
    ],
  },
];

Into this:

const array = [
  { data: 1660953600, value: 0.07 },
  { data: 1661040000, value: 0.062 },
  { data: 1661126400, value: 0.06 },
  { data: 1661212800, value: 0.0725 },
];

My attempt:

const arri = dataSet.map((data) => ({
  data: data.x.map((data) => data),
  value: data.y,
}));

>Solution :

I hope it will help you..

const array = dataSet[0].x.map((x, i) => ({ data: x, value: dataSet[0].y[i] }));

What do you think about it ?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading