0

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.

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

    

1 Comment

Noted and thank you, it gave me an insight using reduce().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.