-2

I'm trying to do an exercise and I need to convert this an array in another specific array, but unfortunately, I couldn't.

I need to convert this array:

    let data = [
    [
      "2020-01-28",
      100
    ],
    [
      "2020-01-27",
      80
    ],
    [
      "2020-01-24",
      70
    ],
    [
      "2020-01-23",
      60
    ]
]

to this array:

    let dataTwo = [
  {
    date: "2020-01-28",
    price: 100
  }, {
    date: "2020-01-27",
    price: 80
  }, {
    date: "2020-01-24",
    price: 70
  }, {
    date: "2020-01-23",
    price: 60
  }
];
0

3 Answers 3

2

Array.map() and destructuring seems to be the best way:

let data = [
    [
      "2020-01-28",
      100
    ],
    [
      "2020-01-27",
      80
    ],
    [
      "2020-01-24",
      70
    ],
    [
      "2020-01-23",
      60
    ]
]

let result = data.map(([data, price]) => ({data,price}));
console.log(result);

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

2 Comments

Concise and clear! +1
very helpful! thanks a lot
1

This should work:

let data = [
    [
      "2020-01-28",
      100
    ],
    [
      "2020-01-27",
      80
    ],
    [
      "2020-01-24",
      70
    ],
    [
      "2020-01-23",
      60
    ]
]

const result = data.map(item => ({ date: item[0], price: item[1] }));
console.log(result);

Comments

0

Try this:

data.map(([v1, v2]) => ({date: v1, price: v2}))

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.