brainfoolong / form-data-json

A zero dependency, cross browser library to easily get or set/manipulate form input values as/from a json object.
https://brainfoolong.github.io/form-data-json
MIT License
57 stars 10 forks source link

Automatic array processing while fromJson #24

Closed Nazar84 closed 2 years ago

Nazar84 commented 2 years ago

Hi! I`v got a form and get a data from DB for It. The data has the same structure:

{
  Company: [
    {
      id: 2,
      name: 'PanamaServ',
      Address: [
        {
          Country: [
            {
              id: 2,
              name: 'USA',
            },
          ],
          address: 'Porkold 11a',
          city: 'NewYork',
          company_id: 2,
          country_id: 2,
          id: 4,
          post_code: 34246,
          region:'ZP',
        },
      ],
      Email: [
        {
          company_id: 2,
          email: 'doubled@ukr.net',
          id: 3,
        },
        {
          company_id: 2,
          email: 'aii@nnn.net',
          id: 2,
        },
      ],
    },
  ],
}

It is necessary to use array because the DB can returns multiple objects. So therefore I should use corresponding names for input fields of the form:

name="Company[0][Address][0][country_id]"
name="Company[0][Email][0][email]"

It is inconvenient to get first element always.

It would be great the fromJson method automatically get first element of an array. And returns callback to process the array in custom function and logging to the console to inform a user if the array has multiple elements. I think it might looks like:

function process_array ( array ) {
    return array[2];
}

It Probably needs an option for this behavior.

brainfoolong commented 2 years ago

Hi. Thanks for reaching out. Unfortunately i don't see any beneficial use of this. It is completely business logic.

The best way is that you process the data before you pass it to fromJson, as you would do anyway with the callback. It make absolutely no difference if you add a separate callback that handles your business logic inside fromJson, or when you do it beforehand and let fromJson do it's thing.

It add's no benefit for anybody and just increase complexity of fromJson for no real advantage. Everything you want to create here requires manual development of a function that manipulate your data.

Nazar84 commented 2 years ago

Thanks! I`v got you and agree with you.