Ad

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.

Ad

Answer

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

Ad
source: stackoverflow.com
Ad