0

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.

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,
}));
1

1 Answer 1

1

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 ?

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

3 Comments

consider adding runnable code snippets
Haha yes sorry @SalwaA.Soliman
// try this const result = [] dataSet.forEach(({x, y}) => { x.forEach((data, index) => result.push({data, value: y[index]})) })

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.