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

How do i map object in array

I want to map the object in the array and access it through the row and col fields

I have the following object array:

const arrayList = [
  {row: 0, col: 0, name:'Ankara'},
  {row: 0, col: 1, name:'Tokyo'},
  {row: 1, col: 0, name:'Munih'},
  {row: 1, col: 1, name:'Basel'},
]

I want to be able to access those elements with a nested array.

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

For example:

arrayMapList[0][0] = {row:0,col:0, name:'Ankara'}

Then I use:

arrayMapList[0][0]

The following should output:

{row:0,col:0, name:'Ankara'}

>Solution :

You need to make nested arrays.

const arrayList = [
  {row:0,col:0, name:'Ankara'},
  {row:0,col:1, name:'Tokyo'},
  {row:1,col:0, name:'Munih'},
  {row:1,col:1, name:'Basel'},
];

const arrayMapList = [];
arrayList.forEach(el => {
  if (!arrayMapList[el.row]) {
    arrayMapList[el.row] = [];
  }
  arrayMapList[el.row][el.col] = el;
});

console.log(arrayMapList[0][1]);
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