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.
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]);