skip to Main Content

I want convert an object to multiple objects in javascript.

this is my object:

const obj =  jQuery('.sts_create form').serializeArray();

console.log logs this:

1
: 
{name: 'target_tag', value: 'a'}
2
: 
{name: 'animation_status', value: 'animation-1'}
3
: 
{name: 'duration', value: ''}
4
: 
{name: 'target_tag', value: 'div'}

But I need it to be similar to this:

{
0 : {
target_tag:'',
animation_status:'',
duration:'',
},
1 : {
target_tag:'',
animation_status:'',
duration:'',
},
...
}

2

Answers


  1. Does this help? Please see code comments for a bit of info on how this works.

    const input_data = [
      {name: 'target_tag', value: 'a'},
      {name: 'animation_status', value: 'animation-1'},
      {name: 'duration', value: ''},
      {name: 'target_tag', value: 'div'},
      {name: 'animation_status', value: 'animation-1'},
      {name: 'duration', value: ''},
    ];
    
    const collate = (input_data) => {
      const result = [{}];
      
      for(const input_info of input_data) {
        // check to see if the last item in the results array has an entry for the
        // current input name, create a new object at the end of the array if it does
        if(result[result.length - 1].hasOwnProperty(input_info.name))
          result.push({});
        
        // add entry to object at end of result array
        result[result.length - 1][input_info.name] = input_info.value;
      }
      
      // convert result array to object
      return Object.fromEntries(Object.entries(result));
    };
    
    console.log(collate(input_data));

    EDIT: updated collate to expect an array rather than an object.

    Login or Signup to reply.
  2. Here’s a solution that self-serialises to an array of objects, you can then reformat that array in various different ways (included).

    As there’s no HTML provided, the first assumption/change is that each "item" (group of fields) is itself each contained with another element – in this case:

    <div class='sts'>
        <input name='..'>
        <input name='..'>
        ...
    </div>
    

    this also allows for easy "user adds or deletes items to the form".

    You can then loop through each wrapper to generate the field outputs and they are then self-contained, rather than a long, flat array that must be broken up.

    $("#addmore").click(() =>
      $(".sts").last().after($(".sts").first().clone())
    );
    
    $("#generate").click(() => {
      let result = [];
      $(".sts").each((_, sts) => {
        let values = {};
        $(sts).find("input,select").each((_, inp) => {
          values[inp.name] = $(inp).val();
        });
        result.push(values);
      });
    
      // Array with eech element an object collated from the form
      console.log(result);
    
      // JSON version of the array, but with no array indicies
      console.log(JSON.stringify(result));
    
      // JSON version of the array with indices
      console.log(JSON.stringify($.extend({}, result)));
    });
    .sts::after {
      content: '';
      display: inline-block;
      height: 0.5em;
      vertical-align: bottom;
      width: 100%;
      margin-right: 0;
      margin-left: 0;
      border-top: 1px solid black
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class='sts'>
      Tag: 
      <input name='target_tag' value='a'><br /> 
      Status:
      <select name='animation_status'>
        <option selected>animation-1</option>
        <option>animation-2</option>
        <option>animation-3</option>
      </select><br /> 
      Duration:
      <input name='duration'><br />
    </div>
    
    <div class='sts'>
      Tag: 
      <input name='target_tag' value='div'><br /> 
      Status:
      <select name='animation_status'>
        <option>animation-1</option>
        <option selected>animation-2</option>
        <option>animation-3</option>
      </select><br /> 
      Duration: 
      <input name='duration'><br />
    </div>
    
    <button id='addmore'>add more</button>
    <button id='generate'>generate</button>

    View results in browser console (rather than snippet console)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search