0

Good morning everyone, is there a method in Javascript to convert from

{ 
 Control[0].Eseguito: "true"
 Control[0].Id:"2"
 Control[0].Nota:""
 Control[1].Eseguito: "true"
 Control[1].Id:"2"
 Control[1].Nota:""
}

to javascript Array?

Control: Array(2)
0: {Id: '1', Eseguito: "true", Nota: ''}
1: {Id: '1', Eseguito: "true", Nota: ''}

EDIT

let myForm = document.getElementById('ControlForm');
var Controls = Object.fromEntries(new FormData(myForm).entries());

In mine ExecControl.cshtml i have situation like this, this is only a small snippet of codes

@{
    int Indice = 0;
}

@for (int i = 0; i < Model.ListControls.Length; i++)
{
    for (int j = 0; j < Model.ListControls[i].Controls.Length; j++)
    {
        ...
        <input type="text" style="width:100%;" name="Control[@Indice].Nota"/>
        input type="text" style="width:100%;" name="Control[@Indice].Id" value="@ListControls[i].Controls.Id"/>
        ...
    }
}
8
  • which form are you using? angular forms? Commented Sep 6, 2022 at 10:29
  • No, i use the classic html form Commented Sep 6, 2022 at 10:30
  • Can you post the code how you are generating Control details from an HTML form? Commented Sep 6, 2022 at 10:32
  • What is the content is Controls at the moment? Your first code block is unclear, is Control[0].Eseguito supposed to be keys in an object? So you actually have: {"Control[0].Eseguito": "true", ... } Commented Sep 6, 2022 at 10:35
  • @Nitheesh, just added. Then in my view i have input type with name like "Controls[@Indice].Eseguito" Commented Sep 6, 2022 at 10:35

1 Answer 1

1

you can convert only [index] type data to array with this method.

var formData = new FormData();
formData.append("Control[0].Id",1);formData.append("Control[0].Nota","Notaval");formData.append("Control[1].Id",2);formData.append("Control[1].Nota","Nott");


function toArray(data){
  var result = [];
  for (const [key,value] of data.entries()) {
      if(!key.includes("[") || !key.includes("]")) {return;}
      var indexVal =  key.indexOf("[") + 1;
      var indexVal2 =  key.indexOf("]");
      var index = parseInt(key.substring(indexVal,indexVal2))
      if(index == NaN){ return;}
      var field = key.split(".")[1]
      result[index] = {...result[index],[field]:value}
    }
   return result;
}
 console.log(toArray(formData));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.