【问题标题】:Modify Json to use into React beautiful Drag and drop修改 Json 使用成 React 漂亮的拖放
【发布时间】:2018-12-03 15:08:58
【问题描述】:

我正在使用 this 库来实现拖放功能。但是,我的 json 是这种格式

[
  {
    "id": "5f7",
    "itemName": "ABC"
  },
  {
    "id": "780",
    "itemName": "CRD"
  },
]

但是,所有的教程点,我都需要这样的东西:

[
  'item1': {
    "id": "5f7",
    "itemName": "ABC"
  },
  'item2': {
    "id": "780",
    "itemName": "CRD"
  }
]

那么我该如何修改我的 json 并为拖放功能添加 id。即使有任何其他方法可以实现这一点,我也非常感激。

【问题讨论】:

  • json2 = json1.map((el, i) => ({ ['item'+i]: el }))

标签: json reactjs drag-and-drop react-beautiful-dnd


【解决方案1】:

您可以使用纯 javascript 执行此操作,使用 map() 循环遍历您的项目数组并创建一个封装该项目的新数组,请参见以下示例:

var currentArray = [{
  "id": "5f7",
  "itemName": "ABC"
},
{
  "id": "780",
  "itemName": "CRD"
}];

var result = "", sep = "";

currentArray.forEach((el, i) => {
  result += sep + "\"item" + (i+1) + "\"";
  result += ": " + JSON.stringify(el);
  sep = ", ";
});

console.log(JSON.parse("{" + result + "}"));

【讨论】:

  • 有什么办法可以让我做这样的事情 {'item1': { "id": "5f7", "itemName": "ABC" }, 'item2': { "id": "780", "itemName": "CRD" }} .所以删除数组并将json对象放入多个json对象中。
  • 你可以使用JSON.stringify,看我更新的sn-p。
  • 您至少必须将每个元素包装在一个数组中。
  • 好吧,我明白了……如果你真的想要一个像上面写的那样的字符串,看看我的 sn-p(result 变量)
猜你喜欢
  • 2015-08-26
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
相关资源
最近更新 更多