S.M. Pat
S.M. Pat

Reputation: 321

Jquery add duplicate array key

I need to create a javascript (jquery) array with duplicated key name like next one

{
    "apple": "type1",
    "apple": "type2",
}

Here is my current code I stack with

var data = {};
jQuery.each(formData, function(i, field) {
    data[field.name] = field.value;
});

In above example field.name is "apple" have different values like "type1" or "type2".

With my current code when same field.name in jQuery.each I got removed/erased "apple":"type1"

Upvotes: 0

Views: 1291

Answers (1)

OliverRadini
OliverRadini

Reputation: 6476

This is not a jQuery problem, but rather it is to do with the nature of objects in javascript. You can't store multiple values on the same key (how would you access them?).

What you can do is store an array on a key, and add to that:

const formData = jQuery('input');
let data = {};

jQuery('button').click(function() {
  data = {}
  jQuery.each(formData, function(i, field) {
    data[field.name] = data.hasOwnProperty(field.name)
      ? [...data[field.name], field.value]
      : [field.value]
  });
  
  console.dir(data);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="a" />
<input name="b" />
<input name="b" />
<button>Test</button>

What the above code does is use an array against a key, and add to that array for each item.

You can do this without jQuery, and without an each, you may or may not prefer this option:

const button = document.querySelector('button');
const getAll = selector => Array.prototype.slice.call(
  document.querySelectorAll(selector)
);

let data = {};

button.onclick = () => {
  data = getAll('input')
    .reduce((result, element) => ({
      ...result,
      [element.name]: result.hasOwnProperty(element.name)
        ? [...result[element.name], element.value]
        : [element.value]
    }), {})
    
  console.dir(data)
}
<input name="a" />
<input name="b" />
<input name="b" />
<button>Test</button>

Upvotes: 1

Related Questions