oguzcan
oguzcan

Reputation: 57

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.

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'}

Upvotes: 1

Views: 87

Answers (4)

Weeby_F33t
Weeby_F33t

Reputation: 11

Consider making your array into a 2D array. For example:

const arrayMapList = [
    ['Ankara', 'Tokyo'],
    ['Munih', 'Basel']
]

let row = 0;
let col = 0;
console.log("Row:" + row + " Col:" + col + " Name: ");//Row:0 Col:0 Name: 
console.log(arrayMapList[row][col]);//Ankara

Upvotes: 1

code
code

Reputation: 6349

Use Array#reduce:

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 result = arrayList.reduce((prev, cur) => (
  (
    prev[cur.row] ??= [], // conditionally assign if it isn't previously defined
    prev[cur.row][cur.col] = cur // assign row and col
  ),
  prev
), []);

console.log(result);

Upvotes: 0

SparrowVic
SparrowVic

Reputation: 279

You can do it with map() method. Just like this:

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 mappedArray = this.arrayList.map(x => ({row: x.row, col: x.col, x}));

Upvotes: -1

Barmar
Barmar

Reputation: 782653

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

Upvotes: 1

Related Questions