0

I have an object which needs to be converted. I am trying to convert the object to FormData to upload a file

Object:

obj{
  a:
  { 
    a1: 'test1',
    a2: 'test2'
  }
  b:
  {
    b1: 'test3',
    c1: 'test4',
  }
}

Converted to:

{
  obj[a][a1]: test1,
  obj[a][a2]: test2,
  obj[b]: binarydata // I want to convet this to binary data 
}

What I have now which is not working:

const formData = new FormData()
Object.keys(object).forEach(key => formData.append(key, object[key]));

I am not trying to flatten array. I am trying to convert it to an object like

obj[key1][key2][..]: value
Prog_CS
  • 33
  • 1
  • 6
  • Possible duplicate of [Flatten object to array?](https://stackoverflow.com/questions/7660765/flatten-object-to-array) – imvain2 Feb 11 '19 at 20:54
  • I am not trying to flatten array; flatten array does something like thisflatten([[1, 2, 3], [4, 5]]); // [1, 2, 3, 4, 5] flatten([[[1, [1.1]], 2, 3], [4, 5]]); // [1, 1.1, 2, 3, 4, 5] which is not what I wanted – Prog_CS Feb 11 '19 at 21:06
  • https://gist.github.com/ghinda/8442a57f22099bdb2e34 – Barmar Feb 11 '19 at 21:15
  • A simpler way might be to convert the object to JSON, and put it into a single `FormData` field, while you use other fields for the file uploads. – Barmar Feb 11 '19 at 21:16
  • https://stackoverflow.com/questions/43334542/convert-json-object-to-formdata-html5-object shows how to do that. – Barmar Feb 11 '19 at 21:17

1 Answers1

0

Try using Object.entries(). For example...

// If this is the object you want to convert to FormData...
const item = {
    description: 'First item',
    price: 13,
    photo: File
};

const formData = new FormData();

Object.entries(item).forEach(([key, value]) => {
    formData.append(key, value);
});

// At this point, you can then pass formData to your handler method

Read more about Object.entries() over here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Kingsley
  • 777
  • 1
  • 12
  • 35