Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 map is throwing error on array of object

const normalizeEventTypes = nextProps.events.space_events.map(obj, i => 
     obj.id
)

I code obj is not defined, my array of object look like this

{
    "space_events": [{
            "id": 1,
            "name": "Anniversaries"
        },
        {
            "id": 2,
            "name": "Brand Rollout"
        }
    }]
}

am I missing something?

like image 641
Alan Jenshen Avatar asked Jun 06 '26 15:06

Alan Jenshen


1 Answers

You forgot to use (), write it like this:

const normalizeEventTypes = nextProps.events.space_events.map((obj, i) => 
     obj.id
)

Reason:

You are using obj and index both parameters in map callback function so you need to use () to wrap the parameters, like this:

a = b.map((i,j) => i)

These () are optional when we want to use only one parameter, like this:

a = b.map(i => i)

Different ways of using map:

1. a.map(i => i + 1); //when index is not required

2.

 a.map(i => {  //when want to do some calculation
       //some calculation
       return //something;
 })

3. a.map((i,j) => i + j) //when want to use the index of item

Check the working snippet:

let data = {
    "space_events": [{
            "id": 1,
            "name": "Anniversaries"
        },
        {
            "id": 2,
            "name": "Brand Rollout"
        }
    ]
}

let result = data.space_events.map((obj,i) => obj.name);

console.log('result', result);
like image 154
Mayank Shukla Avatar answered Jun 08 '26 05:06

Mayank Shukla