I have a problem with the following logic in Javascript.
I have the following array, that have dynamic number of indexes, in this example I write one array with 2 indexes.
[[S,Blue],[M,Red],[L,Yellow]
I want to have this structure:
{ 0: [S,M,L], 1: [Blue,Red,Yellow] }
The numbers are the indexes of first group of array, what can I do?
I tried with for and map function but I don’t have the correct Logic
Advertisement
Answer
You can do this easily by first creating an object with Object.fromEntries()
, then using Object.keys()
and Object.values()
to create an array.
function convertData(data) { const obj = Object.fromEntries(data); return [Object.keys(obj), Object.values(obj)]; } const data = [['S', 'Blue'], ['M', 'Red'], ['L', 'Yellow']] console.log(convertData(data))
Note: an object with numerical keys is the same as an array, therefore, you only need to create an array to fulfill the requirement.