[Vuejs]-How to set one more level in Object of a not predefined item?

2đź‘Ť

To change the format, change in the location it assigns the property value:

Object.assign(data, (_Object$assign = {}, _Object$assign[key] = {text: val}, _Object$assign));
// -------------------------------------------------------------^^^^^^^^^^^

Instead of a string (val), assign the object in the format you want ({text: val}).

Updated CodePen.

If you can use modern (ES6) JavaScript, there’s a much shorter notation for that:

var [key, val] = _ref;
Object.assign(data, {[key]: {text: val}});

CodePen here.

Or (because you are using FormData#entries() you do are using modern JS):

var formData = Array.from(new FormData(this.$refs['form']).entries());
var data = Object.assign(...formData.map(([key, val]) => ({[key]: {text: val}})));

console.log(JSON.stringify(data));

Targetting IE10 and above

To target IE10 and above you’ll need polyfills. The problem is not the syntax, but the absence of functions like .entries(), that will be added by the polyfills. To use the least amount possible of polyfills, you’ll have to iterate the iterator “manually” (kind of like you are already). For more info, check this answer.

👤acdcjunior

0đź‘Ť

You can do the whole construction much more simply:

onSubmit: function () {

  const dataForm = new FormData(this.$refs['form']);
  const data = {};

  for (const i of dataForm.entries()) {
    data[i[0]] = { text: i[1] }
  }

  console.log(JSON.stringify(data));

}
👤Roy J

Leave a comment