Ervan Rahadian Hakim
Ervan Rahadian Hakim

Reputation: 21

How do the map function that return an object with modified keys? (JS, React.js)

I am trying to create an object with modified keys after map() function (the data is from API), here is my code:

    const getData = mySchedule.schedules.map((data) => ({
      [data.id]: false,
    }));
    setCheckId(getData);

This code return:

enter image description here

And I want this output:

enter image description here

Do you have any solution for this case? thank you.

Upvotes: 0

Views: 599

Answers (2)

Lucas Santos
Lucas Santos

Reputation: 3261

The above answer is correct, but let's dive deep into the problem first:

The map function returns an Array, what you want is an Object. The map function applies the callback for every element and returns a new array of elements modified by the callback function. What are you seeing is the array returned by the map function, note that 1,2,3,4is the index position of the array. Read more about the function map here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

The output that you want is an object, but as we have learned before the map function always returns an array with new elements resulting from your map function callback.

If you want an object that are many ways to achieve that, you can loop through the array and add properties to the object.

If you want to understand more and dive into array methods, you can even achieve that using reduce method, therefore the first answer is simpler:

     /* Another example using reducer */
    
    const data = [ {10:false,20:false}];
    
    const reducer = (accumulator, currentValue) => currentValue[accumulator] = false;

  setCheckId(data.reduce(reducer));

    

Upvotes: 1

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7156

Solution:

  1. Create an object => const getData = {};
  2. Iterate => mySchedule.schedules
  3. Set id as a key and false as value => getData[item.id] = false;
const getData = {};

mySchedule.schedules.forEach(item => {
   getData[item.id] = false;
});

setCheckId(getData);

Upvotes: 1

Related Questions