Search code examples
jsonreactjsdrag-and-dropreact-beautiful-dnd

Modify Json to use into React beautiful Drag and drop


I am using this library for react drag and drop functionality. However, my json is in this format

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

However, all the tutorial points, i will need something like this:

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

So how can i modify my json and add id for drag and drop functionalities. Even if there is any other way of achieving this then i really appreciate that.


Solution

  • You can do this with plain javascript, loop through your item's array with map() and create a new array that encapsulates the item, see following example:

    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 + "}"));