【问题标题】:How do create this type of json reponse in React Js (Node Js API)如何在 React Js(Node Js API)中创建这种类型的 json 响应
【发布时间】:2021-01-06 18:52:30
【问题描述】:

我得到的节点 js API 响应

[
    {
        "selected": true,
        "date": "2021-01-15",
        "selectedColor": "#2ecc71"
    },
    {
        "selected": true,
        "date": "2021-01-16",
        "selectedColor": "#e74c3c"
    },
]

我想要的 React Js (react-native-calendars) 的 Node Js API 响应

markedDates={{
    '2021-01-15': {selected: true, selectedColor: '#e74c3c'},
    '2021-01-16': {selected: true, selectedColor: '#2980b9'}
}}

【问题讨论】:

  • 您是否尝试过将响应处理成您想要的形式?发生了什么?

标签: javascript node.js reactjs react-native-calendars


【解决方案1】:

使用 ES6 的工作代码:

const input = [
  {
      "selected": true,
      "date": "2021-01-15",
      "selectedColor": "#2ecc71"
  },
  {
      "selected": true,
      "date": "2021-01-16",
      "selectedColor": "#e74c3c"
  },
]

const format = input => {
  const obj = {};
  input.forEach(inp => {
    const { selected, date, selectedColor } = inp;
    obj[date] = { selected, selectedColor };
  });
  return obj;
}

console.log(format(input));

【讨论】:

    【解决方案2】:

    您可以使用reduce 将输入数组转换为所需的格式,如下所示:

    const data = [
        {
            "selected": true,
            "date": "2021-01-15",
            "selectedColor": "#2ecc71"
        },
        {
            "selected": true,
            "date": "2021-01-16",
            "selectedColor": "#e74c3c"
        },
    ];
    
    const markedDates = data.reduce((a, c) => ({
        ...a, 
        [c.date]: { 
            selected: c.selected, 
            selectedColor: c.selectedColor
        }
    }), {});
    

    reduce 操作迭代输入数组,在这种情况下,我们将当前项的键(示例中为c)附加到累积值(示例中为a)。我们通过使用新的 ES6 运算符进一步缩短代码,例如返回一个对象字面量和使用扩展运算符which is also showcased on the JS docs

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 2020-11-15
      • 2020-09-23
      • 2020-01-10
      • 1970-01-01
      • 2022-12-29
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      相关资源
      最近更新 更多