简体   繁体   English

map function 如何返回带有修改密钥的 object? (JS,React.js)

[英]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:我正在尝试在map() function (数据来自 API)之后创建一个带有修改键的 object,这是我的代码:

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

This code return:此代码返回:

在此处输入图像描述

And I want this output:我想要这个 output:

在此处输入图像描述

Do you have any solution for this case?您对此案有任何解决方案吗? thank you.谢谢你。

Solution:解决方案:

  1. Create an object => const getData = {};创建一个 object => const getData = {};
  2. Iterate => mySchedule.schedules迭代 => mySchedule.schedules
  3. Set id as a key and false as value => getData[item.id] = false;将 id 设置为 key 并将 false 设置为 value => getData[item.id] = false;
const getData = {};

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

setCheckId(getData);

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 . map function 返回一个Array ,你想要的是一个Object The map function applies the callback for every element and returns a new array of elements modified by the callback function. map function 对每个元素应用回调并返回由回调 function 修改的新元素数组。 What are you seeing is the array returned by the map function, note that 1,2,3,4 is the index position of the array.你看到的是map function返回的数组,注意1,2,3,4是数组的索引position。 Read more about the function map here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map在此处阅读有关 function map 的更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

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. 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.如果你想要一个 object 有很多方法来实现它,你可以遍历数组并将属性添加到 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:如果您想了解更多并深入研究数组方法,您甚至可以使用reduce方法来实现,因此第一个答案更简单:

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

  setCheckId(data.reduce(reducer));

    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM